calc-nlfit.el 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. ;;; calc-nlfit.el --- nonlinear curve fitting for Calc
  2. ;; Copyright (C) 2007-2017 Free Software Foundation, Inc.
  3. ;; This file is part of GNU Emacs.
  4. ;; GNU Emacs is free software: you can redistribute it and/or modify
  5. ;; it under the terms of the GNU General Public License as published by
  6. ;; the Free Software Foundation, either version 3 of the License, or
  7. ;; (at your option) any later version.
  8. ;; GNU Emacs 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. ;; You should have received a copy of the GNU General Public License
  13. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  14. ;;; Commentary:
  15. ;; This code uses the Levenberg-Marquardt method, as described in
  16. ;; _Numerical Analysis_ by H. R. Schwarz, to fit data to
  17. ;; nonlinear curves. Currently, the only the following curves are
  18. ;; supported:
  19. ;; The logistic S curve, y=a/(1+exp(b*(t-c)))
  20. ;; Here, y is usually interpreted as the population of some
  21. ;; quantity at time t. So we will think of the data as consisting
  22. ;; of quantities q0, q1, ..., qn and their respective times
  23. ;; t0, t1, ..., tn.
  24. ;; The logistic bell curve, y=A*exp(B*(t-C))/(1+exp(B*(t-C)))^2
  25. ;; Note that this is the derivative of the formula for the S curve.
  26. ;; We get A=-a*b, B=b and C=c. Here, y is interpreted as the rate
  27. ;; of growth of a population at time t. So we will think of the
  28. ;; data as consisting of rates p0, p1, ..., pn and their
  29. ;; respective times t0, t1, ..., tn.
  30. ;; The Hubbert Linearization, y/x=A*(1-x/B)
  31. ;; Here, y is thought of as the rate of growth of a population
  32. ;; and x represents the actual population. This is essentially
  33. ;; the differential equation describing the actual population.
  34. ;; The Levenberg-Marquardt method is an iterative process: it takes
  35. ;; an initial guess for the parameters and refines them. To get an
  36. ;; initial guess for the parameters, we'll use a method described by
  37. ;; Luis de Sousa in "Hubbert's Peak Mathematics". The idea is that
  38. ;; given quantities Q and the corresponding rates P, they should
  39. ;; satisfy P/Q= mQ+a. We can use the parameter a for an
  40. ;; approximation for the parameter a in the S curve, and
  41. ;; approximations for b and c are found using least squares on the
  42. ;; linearization log((a/y)-1) = log(bb) + cc*t of
  43. ;; y=a/(1+bb*exp(cc*t)), which is equivalent to the above s curve
  44. ;; formula, and then translating it to b and c. From this, we can
  45. ;; also get approximations for the bell curve parameters.
  46. ;;; Code:
  47. (require 'calc-arith)
  48. (require 'calcalg3)
  49. ;; Declare functions which are defined elsewhere.
  50. (declare-function calc-get-fit-variables "calcalg3" (nv nc &optional defv defc with-y homog))
  51. (declare-function math-map-binop "calcalg3" (binop args1 args2))
  52. (defun math-nlfit-least-squares (xdata ydata &optional sdata sigmas)
  53. "Return the parameters A and B for the best least squares fit y=a+bx."
  54. (let* ((n (length xdata))
  55. (s2data (if sdata
  56. (mapcar 'calcFunc-sqr sdata)
  57. (make-list n 1)))
  58. (S (if sdata 0 n))
  59. (Sx 0)
  60. (Sy 0)
  61. (Sxx 0)
  62. (Sxy 0)
  63. D)
  64. (while xdata
  65. (let ((x (car xdata))
  66. (y (car ydata))
  67. (s (car s2data)))
  68. (setq Sx (math-add Sx (if s (math-div x s) x)))
  69. (setq Sy (math-add Sy (if s (math-div y s) y)))
  70. (setq Sxx (math-add Sxx (if s (math-div (math-mul x x) s)
  71. (math-mul x x))))
  72. (setq Sxy (math-add Sxy (if s (math-div (math-mul x y) s)
  73. (math-mul x y))))
  74. (if sdata
  75. (setq S (math-add S (math-div 1 s)))))
  76. (setq xdata (cdr xdata))
  77. (setq ydata (cdr ydata))
  78. (setq s2data (cdr s2data)))
  79. (setq D (math-sub (math-mul S Sxx) (math-mul Sx Sx)))
  80. (let ((A (math-div (math-sub (math-mul Sxx Sy) (math-mul Sx Sxy)) D))
  81. (B (math-div (math-sub (math-mul S Sxy) (math-mul Sx Sy)) D)))
  82. (if sigmas
  83. (let ((C11 (math-div Sxx D))
  84. (C12 (math-neg (math-div Sx D)))
  85. (C22 (math-div S D)))
  86. (list (list 'sdev A (calcFunc-sqrt C11))
  87. (list 'sdev B (calcFunc-sqrt C22))
  88. (list 'vec
  89. (list 'vec C11 C12)
  90. (list 'vec C12 C22))))
  91. (list A B)))))
  92. ;;; The methods described by de Sousa require the cumulative data qdata
  93. ;;; and the rates pdata. We will assume that we are given either
  94. ;;; qdata and the corresponding times tdata, or pdata and the corresponding
  95. ;;; tdata. The following two functions will find pdata or qdata,
  96. ;;; given the other..
  97. ;;; First, given two lists; one of values q0, q1, ..., qn and one of
  98. ;;; corresponding times t0, t1, ..., tn; return a list
  99. ;;; p0, p1, ..., pn of the rates of change of the qi with respect to t.
  100. ;;; p0 is the right hand derivative (q1 - q0)/(t1 - t0).
  101. ;;; pn is the left hand derivative (qn - q(n-1))/(tn - t(n-1)).
  102. ;;; The other pis are the averages of the two:
  103. ;;; (1/2)((qi - q(i-1))/(ti - t(i-1)) + (q(i+1) - qi)/(t(i+1) - ti)).
  104. (defun math-nlfit-get-rates-from-cumul (tdata qdata)
  105. (let ((pdata (list
  106. (math-div
  107. (math-sub (nth 1 qdata)
  108. (nth 0 qdata))
  109. (math-sub (nth 1 tdata)
  110. (nth 0 tdata))))))
  111. (while (> (length qdata) 2)
  112. (setq pdata
  113. (cons
  114. (math-mul
  115. '(float 5 -1)
  116. (math-add
  117. (math-div
  118. (math-sub (nth 2 qdata)
  119. (nth 1 qdata))
  120. (math-sub (nth 2 tdata)
  121. (nth 1 tdata)))
  122. (math-div
  123. (math-sub (nth 1 qdata)
  124. (nth 0 qdata))
  125. (math-sub (nth 1 tdata)
  126. (nth 0 tdata)))))
  127. pdata))
  128. (setq qdata (cdr qdata)))
  129. (setq pdata
  130. (cons
  131. (math-div
  132. (math-sub (nth 1 qdata)
  133. (nth 0 qdata))
  134. (math-sub (nth 1 tdata)
  135. (nth 0 tdata)))
  136. pdata))
  137. (reverse pdata)))
  138. ;;; Next, given two lists -- one of rates p0, p1, ..., pn and one of
  139. ;;; corresponding times t0, t1, ..., tn -- and an initial values q0,
  140. ;;; return a list q0, q1, ..., qn of the cumulative values.
  141. ;;; q0 is the initial value given.
  142. ;;; For i>0, qi is computed using the trapezoid rule:
  143. ;;; qi = q(i-1) + (1/2)(pi + p(i-1))(ti - t(i-1))
  144. (defun math-nlfit-get-cumul-from-rates (tdata pdata q0)
  145. (let* ((qdata (list q0)))
  146. (while (cdr pdata)
  147. (setq qdata
  148. (cons
  149. (math-add (car qdata)
  150. (math-mul
  151. (math-mul
  152. '(float 5 -1)
  153. (math-add (nth 1 pdata) (nth 0 pdata)))
  154. (math-sub (nth 1 tdata)
  155. (nth 0 tdata))))
  156. qdata))
  157. (setq pdata (cdr pdata))
  158. (setq tdata (cdr tdata)))
  159. (reverse qdata)))
  160. ;;; Given the qdata, pdata and tdata, find the parameters
  161. ;;; a, b and c that fit q = a/(1+b*exp(c*t)).
  162. ;;; a is found using the method described by de Sousa.
  163. ;;; b and c are found using least squares on the linearization
  164. ;;; log((a/q)-1) = log(b) + c*t
  165. ;;; In some cases (where the logistic curve may well be the wrong
  166. ;;; model), the computed a will be less than or equal to the maximum
  167. ;;; value of q in qdata; in which case the above linearization won't work.
  168. ;;; In this case, a will be replaced by a number slightly above
  169. ;;; the maximum value of q.
  170. (defun math-nlfit-find-qmax (qdata pdata tdata)
  171. (let* ((ratios (math-map-binop 'math-div pdata qdata))
  172. (lsdata (math-nlfit-least-squares ratios tdata))
  173. (qmax (math-max-list (car qdata) (cdr qdata)))
  174. (a (math-neg (math-div (nth 1 lsdata) (nth 0 lsdata)))))
  175. (if (math-lessp a qmax)
  176. (math-add '(float 5 -1) qmax)
  177. a)))
  178. (defun math-nlfit-find-logistic-parameters (qdata pdata tdata)
  179. (let* ((a (math-nlfit-find-qmax qdata pdata tdata))
  180. (newqdata
  181. (mapcar (lambda (q) (calcFunc-ln (math-sub (math-div a q) 1)))
  182. qdata))
  183. (bandc (math-nlfit-least-squares tdata newqdata)))
  184. (list
  185. a
  186. (calcFunc-exp (nth 0 bandc))
  187. (nth 1 bandc))))
  188. ;;; Next, given the pdata and tdata, we can find the qdata if we know q0.
  189. ;;; We first try to find q0, using the fact that when p takes on its largest
  190. ;;; value, q is half of its maximum value. So we'll find the maximum value
  191. ;;; of q given various q0, and use bisection to approximate the correct q0.
  192. ;;; First, given pdata and tdata, find what half of qmax would be if q0=0.
  193. (defun math-nlfit-find-qmaxhalf (pdata tdata)
  194. (let ((pmax (math-max-list (car pdata) (cdr pdata)))
  195. (qmh 0))
  196. (while (math-lessp (car pdata) pmax)
  197. (setq qmh
  198. (math-add qmh
  199. (math-mul
  200. (math-mul
  201. '(float 5 -1)
  202. (math-add (nth 1 pdata) (nth 0 pdata)))
  203. (math-sub (nth 1 tdata)
  204. (nth 0 tdata)))))
  205. (setq pdata (cdr pdata))
  206. (setq tdata (cdr tdata)))
  207. qmh))
  208. ;;; Next, given pdata and tdata, approximate q0.
  209. (defun math-nlfit-find-q0 (pdata tdata)
  210. (let* ((qhalf (math-nlfit-find-qmaxhalf pdata tdata))
  211. (q0 (math-mul 2 qhalf))
  212. (qdata (math-nlfit-get-cumul-from-rates tdata pdata q0)))
  213. (while (math-lessp (math-nlfit-find-qmax
  214. (mapcar
  215. (lambda (q) (math-add q0 q))
  216. qdata)
  217. pdata tdata)
  218. (math-mul
  219. '(float 5 -1)
  220. (math-add
  221. q0
  222. qhalf)))
  223. (setq q0 (math-add q0 qhalf)))
  224. (let* ((qmin (math-sub q0 qhalf))
  225. (qmax q0)
  226. (qt (math-nlfit-find-qmax
  227. (mapcar
  228. (lambda (q) (math-add q0 q))
  229. qdata)
  230. pdata tdata))
  231. (i 0))
  232. (while (< i 10)
  233. (setq q0 (math-mul '(float 5 -1) (math-add qmin qmax)))
  234. (if (math-lessp
  235. (math-nlfit-find-qmax
  236. (mapcar
  237. (lambda (q) (math-add q0 q))
  238. qdata)
  239. pdata tdata)
  240. (math-mul '(float 5 -1) (math-add qhalf q0)))
  241. (setq qmin q0)
  242. (setq qmax q0))
  243. (setq i (1+ i)))
  244. (math-mul '(float 5 -1) (math-add qmin qmax)))))
  245. ;;; To improve the approximations to the parameters, we can use
  246. ;;; Marquardt method as described in Schwarz's book.
  247. ;;; Small numbers used in the Givens algorithm
  248. (defvar math-nlfit-delta '(float 1 -8))
  249. (defvar math-nlfit-epsilon '(float 1 -5))
  250. ;;; Maximum number of iterations
  251. (defvar math-nlfit-max-its 100)
  252. ;;; Next, we need some functions for dealing with vectors and
  253. ;;; matrices. For convenience, we'll work with Emacs lists
  254. ;;; as vectors, rather than Calc's vectors.
  255. (defun math-nlfit-set-elt (vec i x)
  256. (setcar (nthcdr (1- i) vec) x))
  257. (defun math-nlfit-get-elt (vec i)
  258. (nth (1- i) vec))
  259. (defun math-nlfit-make-matrix (i j)
  260. (let ((row (make-list j 0))
  261. (mat nil)
  262. (k 0))
  263. (while (< k i)
  264. (setq mat (cons (copy-sequence row) mat))
  265. (setq k (1+ k)))
  266. mat))
  267. (defun math-nlfit-set-matx-elt (mat i j x)
  268. (setcar (nthcdr (1- j) (nth (1- i) mat)) x))
  269. (defun math-nlfit-get-matx-elt (mat i j)
  270. (nth (1- j) (nth (1- i) mat)))
  271. ;;; For solving the linearized system.
  272. ;;; (The Givens method, from Schwarz.)
  273. (defun math-nlfit-givens (C d)
  274. (let* ((C (copy-tree C))
  275. (d (copy-tree d))
  276. (n (length (car C)))
  277. (N (length C))
  278. (j 1)
  279. (r (make-list N 0))
  280. (x (make-list N 0))
  281. w
  282. gamma
  283. sigma
  284. rho)
  285. (while (<= j n)
  286. (let ((i (1+ j)))
  287. (while (<= i N)
  288. (let ((cij (math-nlfit-get-matx-elt C i j))
  289. (cjj (math-nlfit-get-matx-elt C j j)))
  290. (when (not (math-equal 0 cij))
  291. (if (math-lessp (calcFunc-abs cjj)
  292. (math-mul math-nlfit-delta (calcFunc-abs cij)))
  293. (setq w (math-neg cij)
  294. gamma 0
  295. sigma 1
  296. rho 1)
  297. (setq w (math-mul
  298. (calcFunc-sign cjj)
  299. (calcFunc-sqrt
  300. (math-add
  301. (math-mul cjj cjj)
  302. (math-mul cij cij))))
  303. gamma (math-div cjj w)
  304. sigma (math-neg (math-div cij w)))
  305. (if (math-lessp (calcFunc-abs sigma) gamma)
  306. (setq rho sigma)
  307. (setq rho (math-div (calcFunc-sign sigma) gamma))))
  308. (setq cjj w
  309. cij rho)
  310. (math-nlfit-set-matx-elt C j j w)
  311. (math-nlfit-set-matx-elt C i j rho)
  312. (let ((k (1+ j)))
  313. (while (<= k n)
  314. (let* ((cjk (math-nlfit-get-matx-elt C j k))
  315. (cik (math-nlfit-get-matx-elt C i k))
  316. (h (math-sub
  317. (math-mul gamma cjk) (math-mul sigma cik))))
  318. (setq cik (math-add
  319. (math-mul sigma cjk)
  320. (math-mul gamma cik)))
  321. (setq cjk h)
  322. (math-nlfit-set-matx-elt C i k cik)
  323. (math-nlfit-set-matx-elt C j k cjk)
  324. (setq k (1+ k)))))
  325. (let* ((di (math-nlfit-get-elt d i))
  326. (dj (math-nlfit-get-elt d j))
  327. (h (math-sub
  328. (math-mul gamma dj)
  329. (math-mul sigma di))))
  330. (setq di (math-add
  331. (math-mul sigma dj)
  332. (math-mul gamma di)))
  333. (setq dj h)
  334. (math-nlfit-set-elt d i di)
  335. (math-nlfit-set-elt d j dj))))
  336. (setq i (1+ i))))
  337. (setq j (1+ j)))
  338. (let ((i n)
  339. s)
  340. (while (>= i 1)
  341. (math-nlfit-set-elt r i 0)
  342. (setq s (math-nlfit-get-elt d i))
  343. (let ((k (1+ i)))
  344. (while (<= k n)
  345. (setq s (math-add s (math-mul (math-nlfit-get-matx-elt C i k)
  346. (math-nlfit-get-elt x k))))
  347. (setq k (1+ k))))
  348. (math-nlfit-set-elt x i
  349. (math-neg
  350. (math-div s
  351. (math-nlfit-get-matx-elt C i i))))
  352. (setq i (1- i))))
  353. (let ((i (1+ n)))
  354. (while (<= i N)
  355. (math-nlfit-set-elt r i (math-nlfit-get-elt d i))
  356. (setq i (1+ i))))
  357. (let ((j n))
  358. (while (>= j 1)
  359. (let ((i N))
  360. (while (>= i (1+ j))
  361. (setq rho (math-nlfit-get-matx-elt C i j))
  362. (if (math-equal rho 1)
  363. (setq gamma 0
  364. sigma 1)
  365. (if (math-lessp (calcFunc-abs rho) 1)
  366. (setq sigma rho
  367. gamma (calcFunc-sqrt
  368. (math-sub 1 (math-mul sigma sigma))))
  369. (setq gamma (math-div 1 (calcFunc-abs rho))
  370. sigma (math-mul (calcFunc-sign rho)
  371. (calcFunc-sqrt
  372. (math-sub 1 (math-mul gamma gamma)))))))
  373. (let ((ri (math-nlfit-get-elt r i))
  374. (rj (math-nlfit-get-elt r j))
  375. h)
  376. (setq h (math-add (math-mul gamma rj)
  377. (math-mul sigma ri)))
  378. (setq ri (math-sub
  379. (math-mul gamma ri)
  380. (math-mul sigma rj)))
  381. (setq rj h)
  382. (math-nlfit-set-elt r i ri)
  383. (math-nlfit-set-elt r j rj))
  384. (setq i (1- i))))
  385. (setq j (1- j))))
  386. x))
  387. (defun math-nlfit-jacobian (grad xlist parms &optional slist)
  388. (let ((j nil))
  389. (while xlist
  390. (let ((row (apply grad (car xlist) parms)))
  391. (setq j
  392. (cons
  393. (if slist
  394. (mapcar (lambda (x) (math-div x (car slist))) row)
  395. row)
  396. j)))
  397. (setq slist (cdr slist))
  398. (setq xlist (cdr xlist)))
  399. (reverse j)))
  400. (defun math-nlfit-make-ident (l n)
  401. (let ((m (math-nlfit-make-matrix n n))
  402. (i 1))
  403. (while (<= i n)
  404. (math-nlfit-set-matx-elt m i i l)
  405. (setq i (1+ i)))
  406. m))
  407. (defun math-nlfit-chi-sq (xlist ylist parms fn &optional slist)
  408. (let ((cs 0))
  409. (while xlist
  410. (let ((c
  411. (math-sub
  412. (apply fn (car xlist) parms)
  413. (car ylist))))
  414. (if slist
  415. (setq c (math-div c (car slist))))
  416. (setq cs
  417. (math-add cs
  418. (math-mul c c))))
  419. (setq xlist (cdr xlist))
  420. (setq ylist (cdr ylist))
  421. (setq slist (cdr slist)))
  422. cs))
  423. (defun math-nlfit-init-lambda (C)
  424. (let ((l 0)
  425. (n (length (car C)))
  426. (N (length C)))
  427. (while C
  428. (let ((row (car C)))
  429. (while row
  430. (setq l (math-add l (math-mul (car row) (car row))))
  431. (setq row (cdr row))))
  432. (setq C (cdr C)))
  433. (calcFunc-sqrt (math-div l (math-mul n N)))))
  434. (defun math-nlfit-make-Ctilda (C l)
  435. (let* ((n (length (car C)))
  436. (bot (math-nlfit-make-ident l n)))
  437. (append C bot)))
  438. (defun math-nlfit-make-d (fn xdata ydata parms &optional sdata)
  439. (let ((d nil))
  440. (while xdata
  441. (setq d (cons
  442. (let ((dd (math-sub (apply fn (car xdata) parms)
  443. (car ydata))))
  444. (if sdata (math-div dd (car sdata)) dd))
  445. d))
  446. (setq xdata (cdr xdata))
  447. (setq ydata (cdr ydata))
  448. (setq sdata (cdr sdata)))
  449. (reverse d)))
  450. (defun math-nlfit-make-dtilda (d n)
  451. (append d (make-list n 0)))
  452. (defun math-nlfit-fit (xlist ylist parms fn grad &optional slist)
  453. (let*
  454. ((C (math-nlfit-jacobian grad xlist parms slist))
  455. (d (math-nlfit-make-d fn xlist ylist parms slist))
  456. (chisq (math-nlfit-chi-sq xlist ylist parms fn slist))
  457. (lambda (math-nlfit-init-lambda C))
  458. (really-done nil)
  459. (iters 0))
  460. (while (and
  461. (not really-done)
  462. (< iters math-nlfit-max-its))
  463. (setq iters (1+ iters))
  464. (let ((done nil))
  465. (while (not done)
  466. (let* ((Ctilda (math-nlfit-make-Ctilda C lambda))
  467. (dtilda (math-nlfit-make-dtilda d (length (car C))))
  468. (zeta (math-nlfit-givens Ctilda dtilda))
  469. (newparms (math-map-binop 'math-add (copy-tree parms) zeta))
  470. (newchisq (math-nlfit-chi-sq xlist ylist newparms fn slist)))
  471. (if (math-lessp newchisq chisq)
  472. (progn
  473. (if (math-lessp
  474. (math-div
  475. (math-sub chisq newchisq) newchisq) math-nlfit-epsilon)
  476. (setq really-done t))
  477. (setq lambda (math-div lambda 10))
  478. (setq chisq newchisq)
  479. (setq parms newparms)
  480. (setq done t))
  481. (setq lambda (math-mul lambda 10)))))
  482. (setq C (math-nlfit-jacobian grad xlist parms slist))
  483. (setq d (math-nlfit-make-d fn xlist ylist parms slist))))
  484. (list chisq parms)))
  485. ;;; The functions that describe our models, and their gradients.
  486. (defun math-nlfit-s-logistic-fn (x a b c)
  487. (math-div a (math-add 1 (math-mul b (calcFunc-exp (math-mul c x))))))
  488. (defun math-nlfit-s-logistic-grad (x a b c)
  489. (let* ((ep (calcFunc-exp (math-mul c x)))
  490. (d (math-add 1 (math-mul b ep)))
  491. (d2 (math-mul d d)))
  492. (list
  493. (math-div 1 d)
  494. (math-neg (math-div (math-mul a ep) d2))
  495. (math-neg (math-div (math-mul a (math-mul b (math-mul x ep))) d2)))))
  496. (defun math-nlfit-b-logistic-fn (x a c d)
  497. (let ((ex (calcFunc-exp (math-mul c (math-sub x d)))))
  498. (math-div
  499. (math-mul a ex)
  500. (math-sqr
  501. (math-add
  502. 1 ex)))))
  503. (defun math-nlfit-b-logistic-grad (x a c d)
  504. (let* ((ex (calcFunc-exp (math-mul c (math-sub x d))))
  505. (ex1 (math-add 1 ex))
  506. (xd (math-sub x d)))
  507. (list
  508. (math-div
  509. ex
  510. (math-sqr ex1))
  511. (math-sub
  512. (math-div
  513. (math-mul a (math-mul xd ex))
  514. (math-sqr ex1))
  515. (math-div
  516. (math-mul 2 (math-mul a (math-mul xd (math-sqr ex))))
  517. (math-pow ex1 3)))
  518. (math-sub
  519. (math-div
  520. (math-mul 2 (math-mul a (math-mul c (math-sqr ex))))
  521. (math-pow ex1 3))
  522. (math-div
  523. (math-mul a (math-mul c ex))
  524. (math-sqr ex1))))))
  525. ;;; Functions to get the final covariance matrix and the sdevs
  526. (defun math-nlfit-find-covar (grad xlist pparms)
  527. (let ((j nil))
  528. (while xlist
  529. (setq j (cons (cons 'vec (apply grad (car xlist) pparms)) j))
  530. (setq xlist (cdr xlist)))
  531. (setq j (cons 'vec (reverse j)))
  532. (setq j
  533. (math-mul
  534. (calcFunc-trn j) j))
  535. (calcFunc-inv j)))
  536. (defun math-nlfit-get-sigmas (grad xlist pparms chisq)
  537. (let* ((sgs nil)
  538. (covar (math-nlfit-find-covar grad xlist pparms))
  539. (n (1- (length covar)))
  540. (N (length xlist))
  541. (i 1))
  542. (when (> N n)
  543. (while (<= i n)
  544. (setq sgs (cons (calcFunc-sqrt (nth i (nth i covar))) sgs))
  545. (setq i (1+ i)))
  546. (setq sgs (reverse sgs)))
  547. (list sgs covar)))
  548. ;;; Now the Calc functions
  549. (defun math-nlfit-s-logistic-params (xdata ydata)
  550. (let ((pdata (math-nlfit-get-rates-from-cumul xdata ydata)))
  551. (math-nlfit-find-logistic-parameters ydata pdata xdata)))
  552. (defun math-nlfit-b-logistic-params (xdata ydata)
  553. (let* ((q0 (math-nlfit-find-q0 ydata xdata))
  554. (qdata (math-nlfit-get-cumul-from-rates xdata ydata q0))
  555. (abc (math-nlfit-find-logistic-parameters qdata ydata xdata))
  556. (B (nth 1 abc))
  557. (C (nth 2 abc))
  558. (A (math-neg
  559. (math-mul
  560. (nth 0 abc)
  561. (math-mul B C))))
  562. (D (math-neg (math-div (calcFunc-ln B) C)))
  563. (A (math-div A B)))
  564. (list A C D)))
  565. ;;; Some functions to turn the parameter lists and variables
  566. ;;; into the appropriate functions.
  567. (defun math-nlfit-s-logistic-solnexpr (pms var)
  568. (let ((a (nth 0 pms))
  569. (b (nth 1 pms))
  570. (c (nth 2 pms)))
  571. (list '/ a
  572. (list '+
  573. 1
  574. (list '*
  575. b
  576. (calcFunc-exp
  577. (list '*
  578. c
  579. var)))))))
  580. (defun math-nlfit-b-logistic-solnexpr (pms var)
  581. (let ((a (nth 0 pms))
  582. (c (nth 1 pms))
  583. (d (nth 2 pms)))
  584. (list '/
  585. (list '*
  586. a
  587. (calcFunc-exp
  588. (list '*
  589. c
  590. (list '- var d))))
  591. (list '^
  592. (list '+
  593. 1
  594. (calcFunc-exp
  595. (list '*
  596. c
  597. (list '- var d))))
  598. 2))))
  599. (defun math-nlfit-enter-result (n prefix vals)
  600. (setq calc-aborted-prefix prefix)
  601. (calc-pop-push-record-list n prefix vals)
  602. (calc-handle-whys))
  603. (defun math-nlfit-fit-curve (fn grad solnexpr initparms &optional sdv)
  604. (calc-slow-wrapper
  605. (let* ((sdevv (or (eq sdv 'calcFunc-efit) (eq sdv 'calcFunc-xfit)))
  606. (calc-display-working-message nil)
  607. (data (calc-top 1))
  608. (xdata (cdr (car (cdr data))))
  609. (ydata (cdr (car (cdr (cdr data)))))
  610. (sdata (if (math-contains-sdev-p ydata)
  611. (mapcar (lambda (x) (math-get-sdev x t)) ydata)
  612. nil))
  613. (ydata (mapcar (lambda (x) (math-get-value x)) ydata))
  614. (calc-curve-varnames nil)
  615. (calc-curve-coefnames nil)
  616. (calc-curve-nvars 1)
  617. (fitvars (calc-get-fit-variables 1 3))
  618. (var (nth 1 calc-curve-varnames))
  619. (parms (cdr calc-curve-coefnames))
  620. (parmguess
  621. (funcall initparms xdata ydata))
  622. (fit (math-nlfit-fit xdata ydata parmguess fn grad sdata))
  623. (finalparms (nth 1 fit))
  624. (sigmacovar
  625. (if sdevv
  626. (math-nlfit-get-sigmas grad xdata finalparms (nth 0 fit))))
  627. (sigmas
  628. (if sdevv
  629. (nth 0 sigmacovar)))
  630. (finalparms
  631. (if sigmas
  632. (math-map-binop
  633. (lambda (x y) (list 'sdev x y)) finalparms sigmas)
  634. finalparms))
  635. (soln (funcall solnexpr finalparms var)))
  636. (let ((calc-fit-to-trail t)
  637. (traillist nil))
  638. (while parms
  639. (setq traillist (cons (list 'calcFunc-eq (car parms) (car finalparms))
  640. traillist))
  641. (setq finalparms (cdr finalparms))
  642. (setq parms (cdr parms)))
  643. (setq traillist (calc-normalize (cons 'vec (nreverse traillist))))
  644. (cond ((eq sdv 'calcFunc-efit)
  645. (math-nlfit-enter-result 1 "efit" soln))
  646. ((eq sdv 'calcFunc-xfit)
  647. (let (sln)
  648. (setq sln
  649. (list 'vec
  650. soln
  651. traillist
  652. (nth 1 sigmacovar)
  653. '(vec)
  654. (nth 0 fit)
  655. (let ((n (length xdata))
  656. (m (length finalparms)))
  657. (if (and sdata (> n m))
  658. (calcFunc-utpc (nth 0 fit)
  659. (- n m))
  660. '(var nan var-nan)))))
  661. (math-nlfit-enter-result 1 "xfit" sln)))
  662. (t
  663. (math-nlfit-enter-result 1 "fit" soln)))
  664. (calc-record traillist "parm")))))
  665. (defun calc-fit-s-shaped-logistic-curve (arg)
  666. (interactive "P")
  667. (math-nlfit-fit-curve 'math-nlfit-s-logistic-fn
  668. 'math-nlfit-s-logistic-grad
  669. 'math-nlfit-s-logistic-solnexpr
  670. 'math-nlfit-s-logistic-params
  671. arg))
  672. (defun calc-fit-bell-shaped-logistic-curve (arg)
  673. (interactive "P")
  674. (math-nlfit-fit-curve 'math-nlfit-b-logistic-fn
  675. 'math-nlfit-b-logistic-grad
  676. 'math-nlfit-b-logistic-solnexpr
  677. 'math-nlfit-b-logistic-params
  678. arg))
  679. (defun calc-fit-hubbert-linear-curve (&optional sdv)
  680. (calc-slow-wrapper
  681. (let* ((sdevv (or (eq sdv 'calcFunc-efit) (eq sdv 'calcFunc-xfit)))
  682. (calc-display-working-message nil)
  683. (data (calc-top 1))
  684. (qdata (cdr (car (cdr data))))
  685. (pdata (cdr (car (cdr (cdr data)))))
  686. (sdata (if (math-contains-sdev-p pdata)
  687. (mapcar (lambda (x) (math-get-sdev x t)) pdata)
  688. nil))
  689. (pdata (mapcar (lambda (x) (math-get-value x)) pdata))
  690. (poverqdata (math-map-binop 'math-div pdata qdata))
  691. (parmvals (math-nlfit-least-squares qdata poverqdata sdata sdevv))
  692. (finalparms (list (nth 0 parmvals)
  693. (math-neg
  694. (math-div (nth 0 parmvals)
  695. (nth 1 parmvals)))))
  696. (calc-curve-varnames nil)
  697. (calc-curve-coefnames nil)
  698. (calc-curve-nvars 1)
  699. (fitvars (calc-get-fit-variables 1 2))
  700. (var (nth 1 calc-curve-varnames))
  701. (parms (cdr calc-curve-coefnames))
  702. (soln (list '* (nth 0 finalparms)
  703. (list '- 1
  704. (list '/ var (nth 1 finalparms))))))
  705. (let ((calc-fit-to-trail t)
  706. (traillist nil))
  707. (setq traillist
  708. (list 'vec
  709. (list 'calcFunc-eq (nth 0 parms) (nth 0 finalparms))
  710. (list 'calcFunc-eq (nth 1 parms) (nth 1 finalparms))))
  711. (cond ((eq sdv 'calcFunc-efit)
  712. (math-nlfit-enter-result 1 "efit" soln))
  713. ((eq sdv 'calcFunc-xfit)
  714. (let (sln
  715. (chisq
  716. (math-nlfit-chi-sq
  717. qdata poverqdata
  718. (list (nth 1 (nth 0 finalparms))
  719. (nth 1 (nth 1 finalparms)))
  720. (lambda (x a b)
  721. (math-mul a
  722. (math-sub
  723. 1
  724. (math-div x b))))
  725. sdata)))
  726. (setq sln
  727. (list 'vec
  728. soln
  729. traillist
  730. (nth 2 parmvals)
  731. (list
  732. 'vec
  733. '(calcFunc-fitdummy 1)
  734. (list 'calcFunc-neg
  735. (list '/
  736. '(calcFunc-fitdummy 1)
  737. '(calcFunc-fitdummy 2))))
  738. chisq
  739. (let ((n (length qdata)))
  740. (if (and sdata (> n 2))
  741. (calcFunc-utpc
  742. chisq
  743. (- n 2))
  744. '(var nan var-nan)))))
  745. (math-nlfit-enter-result 1 "xfit" sln)))
  746. (t
  747. (math-nlfit-enter-result 1 "fit" soln)))
  748. (calc-record traillist "parm")))))
  749. (provide 'calc-nlfit)