_odrpack.py 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  1. """
  2. Python wrappers for Orthogonal Distance Regression (ODRPACK).
  3. Notes
  4. =====
  5. * Array formats -- FORTRAN stores its arrays in memory column first, i.e., an
  6. array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,
  7. NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For
  8. efficiency and convenience, the input and output arrays of the fitting
  9. function (and its Jacobians) are passed to FORTRAN without transposition.
  10. Therefore, where the ODRPACK documentation says that the X array is of shape
  11. (N, M), it will be passed to the Python function as an array of shape (M, N).
  12. If M==1, the 1-D case, then nothing matters; if M>1, then your
  13. Python functions will be dealing with arrays that are indexed in reverse of
  14. the ODRPACK documentation. No real issue, but watch out for your indexing of
  15. the Jacobians: the i,jth elements (@f_i/@x_j) evaluated at the nth
  16. observation will be returned as jacd[j, i, n]. Except for the Jacobians, it
  17. really is easier to deal with x[0] and x[1] than x[:,0] and x[:,1]. Of course,
  18. you can always use the transpose() function from SciPy explicitly.
  19. * Examples -- See the accompanying file test/test.py for examples of how to set
  20. up fits of your own. Some are taken from the User's Guide; some are from
  21. other sources.
  22. * Models -- Some common models are instantiated in the accompanying module
  23. models.py . Contributions are welcome.
  24. Credits
  25. =======
  26. * Thanks to Arnold Moene and Gerard Vermeulen for fixing some killer bugs.
  27. Robert Kern
  28. robert.kern@gmail.com
  29. """
  30. import os
  31. from threading import Lock
  32. import numpy as np
  33. from warnings import warn
  34. from scipy.odr import __odrpack
  35. __all__ = ['odr', 'OdrWarning', 'OdrError', 'OdrStop',
  36. 'Data', 'RealData', 'Model', 'Output', 'ODR',
  37. 'odr_error', 'odr_stop']
  38. odr = __odrpack.odr
  39. ODR_LOCK = Lock()
  40. class OdrWarning(UserWarning):
  41. """
  42. Warning indicating that the data passed into
  43. ODR will cause problems when passed into 'odr'
  44. that the user should be aware of.
  45. .. deprecated:: 1.17.0
  46. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  47. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  48. instead.
  49. """
  50. pass
  51. class OdrError(Exception):
  52. """
  53. Exception indicating an error in fitting.
  54. .. deprecated:: 1.17.0
  55. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  56. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  57. instead.
  58. This is raised by `~scipy.odr.odr` if an error occurs during fitting.
  59. """
  60. pass
  61. class OdrStop(Exception):
  62. """
  63. Exception stopping fitting.
  64. .. deprecated:: 1.17.0
  65. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  66. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  67. instead.
  68. You can raise this exception in your objective function to tell
  69. `~scipy.odr.odr` to stop fitting.
  70. """
  71. pass
  72. # Backwards compatibility
  73. odr_error = OdrError
  74. odr_stop = OdrStop
  75. __odrpack._set_exceptions(OdrError, OdrStop)
  76. def _conv(obj, dtype=None):
  77. """ Convert an object to the preferred form for input to the odr routine.
  78. """
  79. if obj is None:
  80. return obj
  81. else:
  82. if dtype is None:
  83. obj = np.asarray(obj)
  84. else:
  85. obj = np.asarray(obj, dtype)
  86. if obj.shape == ():
  87. # Scalar.
  88. return obj.dtype.type(obj)
  89. else:
  90. return obj
  91. def _report_error(info):
  92. """ Interprets the return code of the odr routine.
  93. Parameters
  94. ----------
  95. info : int
  96. The return code of the odr routine.
  97. Returns
  98. -------
  99. problems : list(str)
  100. A list of messages about why the odr() routine stopped.
  101. """
  102. stopreason = ('Blank',
  103. 'Sum of squares convergence',
  104. 'Parameter convergence',
  105. 'Both sum of squares and parameter convergence',
  106. 'Iteration limit reached')[info % 5]
  107. if info >= 5:
  108. # questionable results or fatal error
  109. I = (info//10000 % 10,
  110. info//1000 % 10,
  111. info//100 % 10,
  112. info//10 % 10,
  113. info % 10)
  114. problems = []
  115. if I[0] == 0:
  116. if I[1] != 0:
  117. problems.append('Derivatives possibly not correct')
  118. if I[2] != 0:
  119. problems.append('Error occurred in callback')
  120. if I[3] != 0:
  121. problems.append('Problem is not full rank at solution')
  122. problems.append(stopreason)
  123. elif I[0] == 1:
  124. if I[1] != 0:
  125. problems.append('N < 1')
  126. if I[2] != 0:
  127. problems.append('M < 1')
  128. if I[3] != 0:
  129. problems.append('NP < 1 or NP > N')
  130. if I[4] != 0:
  131. problems.append('NQ < 1')
  132. elif I[0] == 2:
  133. if I[1] != 0:
  134. problems.append('LDY and/or LDX incorrect')
  135. if I[2] != 0:
  136. problems.append('LDWE, LD2WE, LDWD, and/or LD2WD incorrect')
  137. if I[3] != 0:
  138. problems.append('LDIFX, LDSTPD, and/or LDSCLD incorrect')
  139. if I[4] != 0:
  140. problems.append('LWORK and/or LIWORK too small')
  141. elif I[0] == 3:
  142. if I[1] != 0:
  143. problems.append('STPB and/or STPD incorrect')
  144. if I[2] != 0:
  145. problems.append('SCLB and/or SCLD incorrect')
  146. if I[3] != 0:
  147. problems.append('WE incorrect')
  148. if I[4] != 0:
  149. problems.append('WD incorrect')
  150. elif I[0] == 4:
  151. problems.append('Error in derivatives')
  152. elif I[0] == 5:
  153. problems.append('Error occurred in callback')
  154. elif I[0] == 6:
  155. problems.append('Numerical error detected')
  156. return problems
  157. else:
  158. return [stopreason]
  159. class Data:
  160. """
  161. The data to fit.
  162. .. deprecated:: 1.17.0
  163. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  164. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  165. instead.
  166. Parameters
  167. ----------
  168. x : array_like
  169. Observed data for the independent variable of the regression
  170. y : array_like, optional
  171. If array-like, observed data for the dependent variable of the
  172. regression. A scalar input implies that the model to be used on
  173. the data is implicit.
  174. we : array_like, optional
  175. If `we` is a scalar, then that value is used for all data points (and
  176. all dimensions of the response variable).
  177. If `we` is a rank-1 array of length q (the dimensionality of the
  178. response variable), then this vector is the diagonal of the covariant
  179. weighting matrix for all data points.
  180. If `we` is a rank-1 array of length n (the number of data points), then
  181. the i'th element is the weight for the i'th response variable
  182. observation (single-dimensional only).
  183. If `we` is a rank-2 array of shape (q, q), then this is the full
  184. covariant weighting matrix broadcast to each observation.
  185. If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the
  186. diagonal of the covariant weighting matrix for the i'th observation.
  187. If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the
  188. full specification of the covariant weighting matrix for each
  189. observation.
  190. If the fit is implicit, then only a positive scalar value is used.
  191. wd : array_like, optional
  192. If `wd` is a scalar, then that value is used for all data points
  193. (and all dimensions of the input variable). If `wd` = 0, then the
  194. covariant weighting matrix for each observation is set to the identity
  195. matrix (so each dimension of each observation has the same weight).
  196. If `wd` is a rank-1 array of length m (the dimensionality of the input
  197. variable), then this vector is the diagonal of the covariant weighting
  198. matrix for all data points.
  199. If `wd` is a rank-1 array of length n (the number of data points), then
  200. the i'th element is the weight for the ith input variable observation
  201. (single-dimensional only).
  202. If `wd` is a rank-2 array of shape (m, m), then this is the full
  203. covariant weighting matrix broadcast to each observation.
  204. If `wd` is a rank-2 array of shape (m, n), then `wd[:,i]` is the
  205. diagonal of the covariant weighting matrix for the ith observation.
  206. If `wd` is a rank-3 array of shape (m, m, n), then `wd[:,:,i]` is the
  207. full specification of the covariant weighting matrix for each
  208. observation.
  209. fix : array_like of ints, optional
  210. The `fix` argument is the same as ifixx in the class ODR. It is an
  211. array of integers with the same shape as data.x that determines which
  212. input observations are treated as fixed. One can use a sequence of
  213. length m (the dimensionality of the input observations) to fix some
  214. dimensions for all observations. A value of 0 fixes the observation,
  215. a value > 0 makes it free.
  216. meta : dict, optional
  217. Free-form dictionary for metadata.
  218. Notes
  219. -----
  220. Each argument is attached to the member of the instance of the same name.
  221. The structures of `x` and `y` are described in the Model class docstring.
  222. If `y` is an integer, then the Data instance can only be used to fit with
  223. implicit models where the dimensionality of the response is equal to the
  224. specified value of `y`.
  225. The `we` argument weights the effect a deviation in the response variable
  226. has on the fit. The `wd` argument weights the effect a deviation in the
  227. input variable has on the fit. To handle multidimensional inputs and
  228. responses easily, the structure of these arguments has the n'th
  229. dimensional axis first. These arguments heavily use the structured
  230. arguments feature of ODRPACK to conveniently and flexibly support all
  231. options. See the ODRPACK User's Guide for a full explanation of how these
  232. weights are used in the algorithm. Basically, a higher value of the weight
  233. for a particular data point makes a deviation at that point more
  234. detrimental to the fit.
  235. """
  236. def __init__(self, x, y=None, we=None, wd=None, fix=None, meta=None):
  237. self.x = _conv(x)
  238. if not isinstance(self.x, np.ndarray):
  239. raise ValueError("Expected an 'ndarray' of data for 'x', "
  240. f"but instead got data of type '{type(self.x).__name__}'")
  241. self.y = _conv(y)
  242. self.we = _conv(we)
  243. self.wd = _conv(wd)
  244. self.fix = _conv(fix)
  245. self.meta = {} if meta is None else meta
  246. def set_meta(self, **kwds):
  247. """ Update the metadata dictionary with the keywords and data provided
  248. by keywords.
  249. Examples
  250. --------
  251. ::
  252. data.set_meta(lab="Ph 7; Lab 26", title="Ag110 + Ag108 Decay")
  253. """
  254. self.meta.update(kwds)
  255. def __getattr__(self, attr):
  256. """ Dispatch attribute access to the metadata dictionary.
  257. """
  258. if attr != "meta" and attr in self.meta:
  259. return self.meta[attr]
  260. else:
  261. raise AttributeError(f"'{attr}' not in metadata")
  262. class RealData(Data):
  263. """
  264. The data, with weightings as actual standard deviations and/or
  265. covariances.
  266. .. deprecated:: 1.17.0
  267. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  268. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  269. instead.
  270. Parameters
  271. ----------
  272. x : array_like
  273. Observed data for the independent variable of the regression
  274. y : array_like, optional
  275. If array-like, observed data for the dependent variable of the
  276. regression. A scalar input implies that the model to be used on
  277. the data is implicit.
  278. sx : array_like, optional
  279. Standard deviations of `x`.
  280. `sx` are standard deviations of `x` and are converted to weights by
  281. dividing 1.0 by their squares.
  282. sy : array_like, optional
  283. Standard deviations of `y`.
  284. `sy` are standard deviations of `y` and are converted to weights by
  285. dividing 1.0 by their squares.
  286. covx : array_like, optional
  287. Covariance of `x`
  288. `covx` is an array of covariance matrices of `x` and are converted to
  289. weights by performing a matrix inversion on each observation's
  290. covariance matrix.
  291. covy : array_like, optional
  292. Covariance of `y`
  293. `covy` is an array of covariance matrices and are converted to
  294. weights by performing a matrix inversion on each observation's
  295. covariance matrix.
  296. fix : array_like, optional
  297. The argument and member fix is the same as Data.fix and ODR.ifixx:
  298. It is an array of integers with the same shape as `x` that
  299. determines which input observations are treated as fixed. One can
  300. use a sequence of length m (the dimensionality of the input
  301. observations) to fix some dimensions for all observations. A value
  302. of 0 fixes the observation, a value > 0 makes it free.
  303. meta : dict, optional
  304. Free-form dictionary for metadata.
  305. Notes
  306. -----
  307. The weights `wd` and `we` are computed from provided values as follows:
  308. `sx` and `sy` are converted to weights by dividing 1.0 by their squares.
  309. For example, ``wd = 1./np.power(`sx`, 2)``.
  310. `covx` and `covy` are arrays of covariance matrices and are converted to
  311. weights by performing a matrix inversion on each observation's covariance
  312. matrix. For example, ``we[i] = np.linalg.inv(covy[i])``.
  313. These arguments follow the same structured argument conventions as wd and
  314. we only restricted by their natures: `sx` and `sy` can't be rank-3, but
  315. `covx` and `covy` can be.
  316. Only set *either* `sx` or `covx` (not both). Setting both will raise an
  317. exception. Same with `sy` and `covy`.
  318. """
  319. def __init__(self, x, y=None, sx=None, sy=None, covx=None, covy=None,
  320. fix=None, meta=None):
  321. if (sx is not None) and (covx is not None):
  322. raise ValueError("cannot set both sx and covx")
  323. if (sy is not None) and (covy is not None):
  324. raise ValueError("cannot set both sy and covy")
  325. # Set flags for __getattr__
  326. self._ga_flags = {}
  327. if sx is not None:
  328. self._ga_flags['wd'] = 'sx'
  329. else:
  330. self._ga_flags['wd'] = 'covx'
  331. if sy is not None:
  332. self._ga_flags['we'] = 'sy'
  333. else:
  334. self._ga_flags['we'] = 'covy'
  335. self.x = _conv(x)
  336. if not isinstance(self.x, np.ndarray):
  337. raise ValueError("Expected an 'ndarray' of data for 'x', "
  338. f"but instead got data of type '{type(self.x).__name__}'")
  339. self.y = _conv(y)
  340. self.sx = _conv(sx)
  341. self.sy = _conv(sy)
  342. self.covx = _conv(covx)
  343. self.covy = _conv(covy)
  344. self.fix = _conv(fix)
  345. self.meta = {} if meta is None else meta
  346. def _sd2wt(self, sd):
  347. """ Convert standard deviation to weights.
  348. """
  349. return 1./np.power(sd, 2)
  350. def _cov2wt(self, cov):
  351. """ Convert covariance matrix(-ices) to weights.
  352. """
  353. from scipy.linalg import inv
  354. if len(cov.shape) == 2:
  355. return inv(cov)
  356. else:
  357. weights = np.zeros(cov.shape, float)
  358. for i in range(cov.shape[-1]): # n
  359. weights[:,:,i] = inv(cov[:,:,i])
  360. return weights
  361. def __getattr__(self, attr):
  362. if attr not in ('wd', 'we'):
  363. if attr != "meta" and attr in self.meta:
  364. return self.meta[attr]
  365. else:
  366. raise AttributeError(f"'{attr}' not in metadata")
  367. else:
  368. lookup_tbl = {('wd', 'sx'): (self._sd2wt, self.sx),
  369. ('wd', 'covx'): (self._cov2wt, self.covx),
  370. ('we', 'sy'): (self._sd2wt, self.sy),
  371. ('we', 'covy'): (self._cov2wt, self.covy)}
  372. func, arg = lookup_tbl[(attr, self._ga_flags[attr])]
  373. if arg is not None:
  374. return func(*(arg,))
  375. else:
  376. return None
  377. class Model:
  378. """
  379. The Model class stores information about the function you wish to fit.
  380. .. deprecated:: 1.17.0
  381. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  382. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  383. instead.
  384. It stores the function itself, at the least, and optionally stores
  385. functions which compute the Jacobians used during fitting. Also, one
  386. can provide a function that will provide reasonable starting values
  387. for the fit parameters possibly given the set of data.
  388. Parameters
  389. ----------
  390. fcn : function
  391. fcn(beta, x) --> y
  392. fjacb : function
  393. Jacobian of fcn wrt the fit parameters beta.
  394. fjacb(beta, x) --> @f_i(x,B)/@B_j
  395. fjacd : function
  396. Jacobian of fcn wrt the (possibly multidimensional) input
  397. variable.
  398. fjacd(beta, x) --> @f_i(x,B)/@x_j
  399. extra_args : tuple, optional
  400. If specified, `extra_args` should be a tuple of extra
  401. arguments to pass to `fcn`, `fjacb`, and `fjacd`. Each will be called
  402. by `apply(fcn, (beta, x) + extra_args)`
  403. estimate : array_like of rank-1
  404. Provides estimates of the fit parameters from the data
  405. estimate(data) --> estbeta
  406. implicit : boolean
  407. If TRUE, specifies that the model
  408. is implicit; i.e `fcn(beta, x)` ~= 0 and there is no y data to fit
  409. against
  410. meta : dict, optional
  411. freeform dictionary of metadata for the model
  412. Notes
  413. -----
  414. Note that the `fcn`, `fjacb`, and `fjacd` operate on NumPy arrays and
  415. return a NumPy array. The `estimate` object takes an instance of the
  416. Data class.
  417. Here are the rules for the shapes of the argument and return
  418. arrays of the callback functions:
  419. `x`
  420. if the input data is single-dimensional, then `x` is rank-1
  421. array; i.e., ``x = array([1, 2, 3, ...]); x.shape = (n,)``
  422. If the input data is multi-dimensional, then `x` is a rank-2 array;
  423. i.e., ``x = array([[1, 2, ...], [2, 4, ...]]); x.shape = (m, n)``.
  424. In all cases, it has the same shape as the input data array passed to
  425. `~scipy.odr.odr`. `m` is the dimensionality of the input data,
  426. `n` is the number of observations.
  427. `y`
  428. if the response variable is single-dimensional, then `y` is a
  429. rank-1 array, i.e., ``y = array([2, 4, ...]); y.shape = (n,)``.
  430. If the response variable is multi-dimensional, then `y` is a rank-2
  431. array, i.e., ``y = array([[2, 4, ...], [3, 6, ...]]); y.shape =
  432. (q, n)`` where `q` is the dimensionality of the response variable.
  433. `beta`
  434. rank-1 array of length `p` where `p` is the number of parameters;
  435. i.e. ``beta = array([B_1, B_2, ..., B_p])``
  436. `fjacb`
  437. if the response variable is multi-dimensional, then the
  438. return array's shape is ``(q, p, n)`` such that ``fjacb(beta,x)[l,k,i] =
  439. d f_l(beta,x)/d B_k`` evaluated at the ith data point. If ``q == 1``, then
  440. the return array is only rank-2 and with shape ``(p, n)``.
  441. `fjacd`
  442. as with fjacb, only the return array's shape is ``(q, m, n)``
  443. such that ``fjacd(beta,x)[l,j,i] = d f_l(beta,x)/d X_j`` at the ith data
  444. point. If ``q == 1``, then the return array's shape is ``(m, n)``. If
  445. ``m == 1``, the shape is (q, n). If `m == q == 1`, the shape is ``(n,)``.
  446. """
  447. def __init__(self, fcn, fjacb=None, fjacd=None,
  448. extra_args=None, estimate=None, implicit=0, meta=None):
  449. self.fcn = fcn
  450. self.fjacb = fjacb
  451. self.fjacd = fjacd
  452. if extra_args is not None:
  453. extra_args = tuple(extra_args)
  454. self.extra_args = extra_args
  455. self.estimate = estimate
  456. self.implicit = implicit
  457. self.meta = meta if meta is not None else {}
  458. def set_meta(self, **kwds):
  459. """ Update the metadata dictionary with the keywords and data provided
  460. here.
  461. Examples
  462. --------
  463. set_meta(name="Exponential", equation="y = a exp(b x) + c")
  464. """
  465. self.meta.update(kwds)
  466. def __getattr__(self, attr):
  467. """ Dispatch attribute access to the metadata.
  468. """
  469. if attr != "meta" and attr in self.meta:
  470. return self.meta[attr]
  471. else:
  472. raise AttributeError(f"'{attr}' not in metadata")
  473. class Output:
  474. """
  475. The Output class stores the output of an ODR run.
  476. .. deprecated:: 1.17.0
  477. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  478. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  479. instead.
  480. Attributes
  481. ----------
  482. beta : ndarray
  483. Estimated parameter values, of shape (q,).
  484. sd_beta : ndarray
  485. Standard deviations of the estimated parameters, of shape (p,).
  486. cov_beta : ndarray
  487. Covariance matrix of the estimated parameters, of shape (p,p).
  488. Note that this `cov_beta` is not scaled by the residual variance
  489. `res_var`, whereas `sd_beta` is. This means
  490. ``np.sqrt(np.diag(output.cov_beta * output.res_var))`` is the same
  491. result as `output.sd_beta`.
  492. delta : ndarray, optional
  493. Array of estimated errors in input variables, of same shape as `x`.
  494. eps : ndarray, optional
  495. Array of estimated errors in response variables, of same shape as `y`.
  496. xplus : ndarray, optional
  497. Array of ``x + delta``.
  498. y : ndarray, optional
  499. Array ``y = fcn(x + delta)``.
  500. res_var : float, optional
  501. Residual variance.
  502. sum_square : float, optional
  503. Sum of squares error.
  504. sum_square_delta : float, optional
  505. Sum of squares of delta error.
  506. sum_square_eps : float, optional
  507. Sum of squares of eps error.
  508. inv_condnum : float, optional
  509. Inverse condition number (cf. ODRPACK UG p. 77).
  510. rel_error : float, optional
  511. Relative error in function values computed within fcn.
  512. work : ndarray, optional
  513. Final work array.
  514. work_ind : dict, optional
  515. Indices into work for drawing out values (cf. ODRPACK UG p. 83).
  516. info : int, optional
  517. Reason for returning, as output by ODRPACK (cf. ODRPACK UG p. 38).
  518. stopreason : list of str, optional
  519. `info` interpreted into English.
  520. Notes
  521. -----
  522. Takes one argument for initialization, the return value from the
  523. function `~scipy.odr.odr`. The attributes listed as "optional" above are
  524. only present if `~scipy.odr.odr` was run with ``full_output=1``.
  525. """
  526. def __init__(self, output):
  527. self.beta = output[0]
  528. self.sd_beta = output[1]
  529. self.cov_beta = output[2]
  530. if len(output) == 4:
  531. # full output
  532. self.__dict__.update(output[3])
  533. self.stopreason = _report_error(self.info)
  534. def pprint(self):
  535. """ Pretty-print important results.
  536. """
  537. print('Beta:', self.beta)
  538. print('Beta Std Error:', self.sd_beta)
  539. print('Beta Covariance:', self.cov_beta)
  540. if hasattr(self, 'info'):
  541. print('Residual Variance:',self.res_var)
  542. print('Inverse Condition #:', self.inv_condnum)
  543. print('Reason(s) for Halting:')
  544. for r in self.stopreason:
  545. print(f' {r}')
  546. class ODR:
  547. """
  548. The ODR class gathers all information and coordinates the running of the
  549. main fitting routine.
  550. .. deprecated:: 1.17.0
  551. `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
  552. `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
  553. instead.
  554. Members of instances of the ODR class have the same names as the arguments
  555. to the initialization routine.
  556. Parameters
  557. ----------
  558. data : Data class instance
  559. instance of the Data class
  560. model : Model class instance
  561. instance of the Model class
  562. Other Parameters
  563. ----------------
  564. beta0 : array_like of rank-1
  565. a rank-1 sequence of initial parameter values. Optional if
  566. model provides an "estimate" function to estimate these values.
  567. delta0 : array_like of floats of rank-1, optional
  568. a (double-precision) float array to hold the initial values of
  569. the errors in the input variables. Must be same shape as data.x
  570. ifixb : array_like of ints of rank-1, optional
  571. sequence of integers with the same length as beta0 that determines
  572. which parameters are held fixed. A value of 0 fixes the parameter,
  573. a value > 0 makes the parameter free.
  574. ifixx : array_like of ints with same shape as data.x, optional
  575. an array of integers with the same shape as data.x that determines
  576. which input observations are treated as fixed. One can use a sequence
  577. of length m (the dimensionality of the input observations) to fix some
  578. dimensions for all observations. A value of 0 fixes the observation,
  579. a value > 0 makes it free.
  580. job : int, optional
  581. an integer telling ODRPACK what tasks to perform. See p. 31 of the
  582. ODRPACK User's Guide if you absolutely must set the value here. Use the
  583. method set_job post-initialization for a more readable interface.
  584. iprint : int, optional
  585. an integer telling ODRPACK what to print. See pp. 33-34 of the
  586. ODRPACK User's Guide if you absolutely must set the value here. Use the
  587. method set_iprint post-initialization for a more readable interface.
  588. errfile : str, optional
  589. string with the filename to print ODRPACK errors to. If the file already
  590. exists, an error will be thrown. The `overwrite` argument can be used to
  591. prevent this. *Do Not Open This File Yourself!*
  592. rptfile : str, optional
  593. string with the filename to print ODRPACK summaries to. If the file
  594. already exists, an error will be thrown. The `overwrite` argument can be
  595. used to prevent this. *Do Not Open This File Yourself!*
  596. ndigit : int, optional
  597. integer specifying the number of reliable digits in the computation
  598. of the function.
  599. taufac : float, optional
  600. float specifying the initial trust region. The default value is 1.
  601. The initial trust region is equal to taufac times the length of the
  602. first computed Gauss-Newton step. taufac must be less than 1.
  603. sstol : float, optional
  604. float specifying the tolerance for convergence based on the relative
  605. change in the sum-of-squares. The default value is eps**(1/2) where eps
  606. is the smallest value such that 1 + eps > 1 for double precision
  607. computation on the machine. sstol must be less than 1.
  608. partol : float, optional
  609. float specifying the tolerance for convergence based on the relative
  610. change in the estimated parameters. The default value is eps**(2/3) for
  611. explicit models and ``eps**(1/3)`` for implicit models. partol must be less
  612. than 1.
  613. maxit : int, optional
  614. integer specifying the maximum number of iterations to perform. For
  615. first runs, maxit is the total number of iterations performed and
  616. defaults to 50. For restarts, maxit is the number of additional
  617. iterations to perform and defaults to 10.
  618. stpb : array_like, optional
  619. sequence (``len(stpb) == len(beta0)``) of relative step sizes to compute
  620. finite difference derivatives wrt the parameters.
  621. stpd : optional
  622. array (``stpd.shape == data.x.shape`` or ``stpd.shape == (m,)``) of relative
  623. step sizes to compute finite difference derivatives wrt the input
  624. variable errors. If stpd is a rank-1 array with length m (the
  625. dimensionality of the input variable), then the values are broadcast to
  626. all observations.
  627. sclb : array_like, optional
  628. sequence (``len(stpb) == len(beta0)``) of scaling factors for the
  629. parameters. The purpose of these scaling factors are to scale all of
  630. the parameters to around unity. Normally appropriate scaling factors
  631. are computed if this argument is not specified. Specify them yourself
  632. if the automatic procedure goes awry.
  633. scld : array_like, optional
  634. array (scld.shape == data.x.shape or scld.shape == (m,)) of scaling
  635. factors for the *errors* in the input variables. Again, these factors
  636. are automatically computed if you do not provide them. If scld.shape ==
  637. (m,), then the scaling factors are broadcast to all observations.
  638. work : ndarray, optional
  639. array to hold the double-valued working data for ODRPACK. When
  640. restarting, takes the value of self.output.work.
  641. iwork : ndarray, optional
  642. array to hold the integer-valued working data for ODRPACK. When
  643. restarting, takes the value of self.output.iwork.
  644. overwrite : bool, optional
  645. If it is True, output files defined by `errfile` and `rptfile` are
  646. overwritten. The default is False.
  647. Attributes
  648. ----------
  649. data : Data
  650. The data for this fit
  651. model : Model
  652. The model used in fit
  653. output : Output
  654. An instance if the Output class containing all of the returned
  655. data from an invocation of ODR.run() or ODR.restart()
  656. """
  657. def __init__(self, data, model, beta0=None, delta0=None, ifixb=None,
  658. ifixx=None, job=None, iprint=None, errfile=None, rptfile=None,
  659. ndigit=None, taufac=None, sstol=None, partol=None, maxit=None,
  660. stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None,
  661. overwrite=False):
  662. self.data = data
  663. self.model = model
  664. if beta0 is None:
  665. if self.model.estimate is not None:
  666. self.beta0 = _conv(self.model.estimate(self.data))
  667. else:
  668. raise ValueError(
  669. "must specify beta0 or provide an estimator with the model"
  670. )
  671. else:
  672. self.beta0 = _conv(beta0)
  673. if ifixx is None and data.fix is not None:
  674. ifixx = data.fix
  675. if overwrite:
  676. # remove output files for overwriting.
  677. if rptfile is not None and os.path.exists(rptfile):
  678. os.remove(rptfile)
  679. if errfile is not None and os.path.exists(errfile):
  680. os.remove(errfile)
  681. self.delta0 = _conv(delta0)
  682. # These really are 32-bit integers in FORTRAN (gfortran), even on 64-bit
  683. # platforms.
  684. # XXX: some other FORTRAN compilers may not agree.
  685. self.ifixx = _conv(ifixx, dtype=np.int32)
  686. self.ifixb = _conv(ifixb, dtype=np.int32)
  687. self.job = job
  688. self.iprint = iprint
  689. self.errfile = errfile
  690. self.rptfile = rptfile
  691. self.ndigit = ndigit
  692. self.taufac = taufac
  693. self.sstol = sstol
  694. self.partol = partol
  695. self.maxit = maxit
  696. self.stpb = _conv(stpb)
  697. self.stpd = _conv(stpd)
  698. self.sclb = _conv(sclb)
  699. self.scld = _conv(scld)
  700. self.work = _conv(work)
  701. self.iwork = _conv(iwork)
  702. self.output = None
  703. self._check()
  704. def _check(self):
  705. """ Check the inputs for consistency, but don't bother checking things
  706. that the builtin function odr will check.
  707. """
  708. x_s = list(self.data.x.shape)
  709. if isinstance(self.data.y, np.ndarray):
  710. y_s = list(self.data.y.shape)
  711. if self.model.implicit:
  712. raise OdrError("an implicit model cannot use response data")
  713. if self.job is not None and (self.job % 10) == 1:
  714. raise OdrError("job parameter requests an implicit model,"
  715. " but an explicit model was passed")
  716. else:
  717. # implicit model with q == self.data.y
  718. y_s = [self.data.y, x_s[-1]]
  719. if not self.model.implicit:
  720. raise OdrError("an explicit model needs response data")
  721. self.set_job(fit_type=1)
  722. if x_s[-1] != y_s[-1]:
  723. raise OdrError("number of observations do not match")
  724. n = x_s[-1]
  725. if len(x_s) == 2:
  726. m = x_s[0]
  727. else:
  728. m = 1
  729. if len(y_s) == 2:
  730. q = y_s[0]
  731. else:
  732. q = 1
  733. p = len(self.beta0)
  734. # permissible output array shapes
  735. fcn_perms = [(q, n)]
  736. fjacd_perms = [(q, m, n)]
  737. fjacb_perms = [(q, p, n)]
  738. if q == 1:
  739. fcn_perms.append((n,))
  740. fjacd_perms.append((m, n))
  741. fjacb_perms.append((p, n))
  742. if m == 1:
  743. fjacd_perms.append((q, n))
  744. if p == 1:
  745. fjacb_perms.append((q, n))
  746. if m == q == 1:
  747. fjacd_perms.append((n,))
  748. if p == q == 1:
  749. fjacb_perms.append((n,))
  750. # try evaluating the supplied functions to make sure they provide
  751. # sensible outputs
  752. arglist = (self.beta0, self.data.x)
  753. if self.model.extra_args is not None:
  754. arglist = arglist + self.model.extra_args
  755. res = self.model.fcn(*arglist)
  756. if res.shape not in fcn_perms:
  757. print(res.shape)
  758. print(fcn_perms)
  759. raise OdrError(f"fcn does not output {y_s}-shaped array")
  760. if self.model.fjacd is not None:
  761. res = self.model.fjacd(*arglist)
  762. if res.shape not in fjacd_perms:
  763. raise OdrError(
  764. f"fjacd does not output {repr((q, m, n))}-shaped array")
  765. if self.model.fjacb is not None:
  766. res = self.model.fjacb(*arglist)
  767. if res.shape not in fjacb_perms:
  768. raise OdrError(
  769. f"fjacb does not output {repr((q, p, n))}-shaped array")
  770. # check shape of delta0
  771. if self.delta0 is not None and self.delta0.shape != self.data.x.shape:
  772. raise OdrError(
  773. f"delta0 is not a {repr(self.data.x.shape)}-shaped array")
  774. if self.data.x.size == 0:
  775. warn("Empty data detected for ODR instance. "
  776. "Do not expect any fitting to occur",
  777. OdrWarning, stacklevel=3)
  778. def _gen_work(self):
  779. """ Generate a suitable work array if one does not already exist.
  780. """
  781. n = self.data.x.shape[-1]
  782. p = self.beta0.shape[0]
  783. if len(self.data.x.shape) == 2:
  784. m = self.data.x.shape[0]
  785. else:
  786. m = 1
  787. if self.model.implicit:
  788. q = self.data.y
  789. elif len(self.data.y.shape) == 2:
  790. q = self.data.y.shape[0]
  791. else:
  792. q = 1
  793. if self.data.we is None:
  794. ldwe = ld2we = 1
  795. elif len(self.data.we.shape) == 3:
  796. ld2we, ldwe = self.data.we.shape[1:]
  797. else:
  798. we = self.data.we
  799. ldwe = 1
  800. ld2we = 1
  801. if we.ndim == 1 and q == 1:
  802. ldwe = n
  803. elif we.ndim == 2:
  804. if we.shape == (q, q):
  805. ld2we = q
  806. elif we.shape == (q, n):
  807. ldwe = n
  808. if self.job % 10 < 2:
  809. # ODR not OLS
  810. lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 6*n*m + 2*n*q*p +
  811. 2*n*q*m + q*q + 5*q + q*(p+m) + ldwe*ld2we*q)
  812. else:
  813. # OLS not ODR
  814. lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 2*n*m + 2*n*q*p +
  815. 5*q + q*(p+m) + ldwe*ld2we*q)
  816. if isinstance(self.work, np.ndarray) and self.work.shape == (lwork,)\
  817. and self.work.dtype.str.endswith('f8'):
  818. # the existing array is fine
  819. return
  820. else:
  821. self.work = np.zeros((lwork,), float)
  822. def set_job(self, fit_type=None, deriv=None, var_calc=None,
  823. del_init=None, restart=None):
  824. """
  825. Sets the "job" parameter is a hopefully comprehensible way.
  826. If an argument is not specified, then the value is left as is. The
  827. default value from class initialization is for all of these options set
  828. to 0.
  829. Parameters
  830. ----------
  831. fit_type : {0, 1, 2} int
  832. 0 -> explicit ODR
  833. 1 -> implicit ODR
  834. 2 -> ordinary least-squares
  835. deriv : {0, 1, 2, 3} int
  836. 0 -> forward finite differences
  837. 1 -> central finite differences
  838. 2 -> user-supplied derivatives (Jacobians) with results
  839. checked by ODRPACK
  840. 3 -> user-supplied derivatives, no checking
  841. var_calc : {0, 1, 2} int
  842. 0 -> calculate asymptotic covariance matrix and fit
  843. parameter uncertainties (V_B, s_B) using derivatives
  844. recomputed at the final solution
  845. 1 -> calculate V_B and s_B using derivatives from last iteration
  846. 2 -> do not calculate V_B and s_B
  847. del_init : {0, 1} int
  848. 0 -> initial input variable offsets set to 0
  849. 1 -> initial offsets provided by user in variable "work"
  850. restart : {0, 1} int
  851. 0 -> fit is not a restart
  852. 1 -> fit is a restart
  853. Notes
  854. -----
  855. The permissible values are different from those given on pg. 31 of the
  856. ODRPACK User's Guide only in that one cannot specify numbers greater than
  857. the last value for each variable.
  858. If one does not supply functions to compute the Jacobians, the fitting
  859. procedure will change deriv to 0, finite differences, as a default. To
  860. initialize the input variable offsets by yourself, set del_init to 1 and
  861. put the offsets into the "work" variable correctly.
  862. """
  863. if self.job is None:
  864. job_l = [0, 0, 0, 0, 0]
  865. else:
  866. job_l = [self.job // 10000 % 10,
  867. self.job // 1000 % 10,
  868. self.job // 100 % 10,
  869. self.job // 10 % 10,
  870. self.job % 10]
  871. if fit_type in (0, 1, 2):
  872. job_l[4] = fit_type
  873. if deriv in (0, 1, 2, 3):
  874. job_l[3] = deriv
  875. if var_calc in (0, 1, 2):
  876. job_l[2] = var_calc
  877. if del_init in (0, 1):
  878. job_l[1] = del_init
  879. if restart in (0, 1):
  880. job_l[0] = restart
  881. self.job = (job_l[0]*10000 + job_l[1]*1000 +
  882. job_l[2]*100 + job_l[3]*10 + job_l[4])
  883. def set_iprint(self, init=None, so_init=None,
  884. iter=None, so_iter=None, iter_step=None, final=None, so_final=None):
  885. """ Set the iprint parameter for the printing of computation reports.
  886. If any of the arguments are specified here, then they are set in the
  887. iprint member. If iprint is not set manually or with this method, then
  888. ODRPACK defaults to no printing. If no filename is specified with the
  889. member rptfile, then ODRPACK prints to stdout. One can tell ODRPACK to
  890. print to stdout in addition to the specified filename by setting the
  891. so_* arguments to this function, but one cannot specify to print to
  892. stdout but not a file since one can do that by not specifying a rptfile
  893. filename.
  894. There are three reports: initialization, iteration, and final reports.
  895. They are represented by the arguments init, iter, and final
  896. respectively. The permissible values are 0, 1, and 2 representing "no
  897. report", "short report", and "long report" respectively.
  898. The argument iter_step (0 <= iter_step <= 9) specifies how often to make
  899. the iteration report; the report will be made for every iter_step'th
  900. iteration starting with iteration one. If iter_step == 0, then no
  901. iteration report is made, regardless of the other arguments.
  902. If the rptfile is None, then any so_* arguments supplied will raise an
  903. exception.
  904. """
  905. if self.iprint is None:
  906. self.iprint = 0
  907. ip = [self.iprint // 1000 % 10,
  908. self.iprint // 100 % 10,
  909. self.iprint // 10 % 10,
  910. self.iprint % 10]
  911. # make a list to convert iprint digits to/from argument inputs
  912. # rptfile, stdout
  913. ip2arg = [[0, 0], # none, none
  914. [1, 0], # short, none
  915. [2, 0], # long, none
  916. [1, 1], # short, short
  917. [2, 1], # long, short
  918. [1, 2], # short, long
  919. [2, 2]] # long, long
  920. if (self.rptfile is None and
  921. (so_init is not None or
  922. so_iter is not None or
  923. so_final is not None)):
  924. raise OdrError(
  925. "no rptfile specified, cannot output to stdout twice")
  926. iprint_l = ip2arg[ip[0]] + ip2arg[ip[1]] + ip2arg[ip[3]]
  927. if init is not None:
  928. iprint_l[0] = init
  929. if so_init is not None:
  930. iprint_l[1] = so_init
  931. if iter is not None:
  932. iprint_l[2] = iter
  933. if so_iter is not None:
  934. iprint_l[3] = so_iter
  935. if final is not None:
  936. iprint_l[4] = final
  937. if so_final is not None:
  938. iprint_l[5] = so_final
  939. if iter_step in range(10):
  940. # 0..9
  941. ip[2] = iter_step
  942. ip[0] = ip2arg.index(iprint_l[0:2])
  943. ip[1] = ip2arg.index(iprint_l[2:4])
  944. ip[3] = ip2arg.index(iprint_l[4:6])
  945. self.iprint = ip[0]*1000 + ip[1]*100 + ip[2]*10 + ip[3]
  946. def run(self):
  947. """ Run the fitting routine with all of the information given and with ``full_output=1``.
  948. Returns
  949. -------
  950. output : Output instance
  951. This object is also assigned to the attribute .output .
  952. """ # noqa: E501
  953. args = (self.model.fcn, self.beta0, self.data.y, self.data.x)
  954. kwds = {'full_output': 1}
  955. kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile',
  956. 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb',
  957. 'stpd', 'sclb', 'scld', 'work', 'iwork']
  958. if self.delta0 is not None and (self.job // 10000) % 10 == 0:
  959. # delta0 provided and fit is not a restart
  960. self._gen_work()
  961. d0 = np.ravel(self.delta0)
  962. self.work[:len(d0)] = d0
  963. # set the kwds from other objects explicitly
  964. if self.model.fjacb is not None:
  965. kwds['fjacb'] = self.model.fjacb
  966. if self.model.fjacd is not None:
  967. kwds['fjacd'] = self.model.fjacd
  968. if self.data.we is not None:
  969. kwds['we'] = self.data.we
  970. if self.data.wd is not None:
  971. kwds['wd'] = self.data.wd
  972. if self.model.extra_args is not None:
  973. kwds['extra_args'] = self.model.extra_args
  974. # implicitly set kwds from self's members
  975. for attr in kwd_l:
  976. obj = getattr(self, attr)
  977. if obj is not None:
  978. kwds[attr] = obj
  979. with ODR_LOCK:
  980. self.output = Output(odr(*args, **kwds))
  981. return self.output
  982. def restart(self, iter=None):
  983. """ Restarts the run with iter more iterations.
  984. Parameters
  985. ----------
  986. iter : int, optional
  987. ODRPACK's default for the number of new iterations is 10.
  988. Returns
  989. -------
  990. output : Output instance
  991. This object is also assigned to the attribute .output .
  992. """
  993. if self.output is None:
  994. raise OdrError("cannot restart: run() has not been called before")
  995. self.set_job(restart=1)
  996. self.work = self.output.work
  997. self.iwork = self.output.iwork
  998. self.maxit = iter
  999. return self.run()