ALGO_Kalman_ATY.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /**
  2. * @file ALGO_Kalman_ATY.c
  3. *
  4. * @param Project ALGO_Algorithm_ATY_LIB
  5. *
  6. * @author ATY
  7. *
  8. * @copyright
  9. * - Copyright 2017 - 2026 MZ-ATY
  10. * - This code follows:
  11. * - MZ-ATY Various Contents Joint Statement -
  12. * <a href="https://mengze.top/MZ-ATY_VCJS">
  13. * https://mengze.top/MZ-ATY_VCJS</a>
  14. * - CC 4.0 BY-NC-SA -
  15. * <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
  16. * https://creativecommons.org/licenses/by-nc-sa/4.0/</a>
  17. * - Your use will be deemed to have accepted the terms of this statement.
  18. *
  19. * @brief functions of Kalman
  20. *
  21. * @version
  22. * - 1_01_220605 > ATY
  23. * -# Preliminary version, first Release
  24. * - 1_02_230108 > ATY
  25. * -# Finish and test 2D
  26. * @see https://www.kalmanfilter.net/
  27. * @see https://github.com/xiahouzuoxin/kalman_filter
  28. * @see https://blog.csdn.net/whereismatrix/article/details/79920748
  29. ********************************************************************************
  30. */
  31. #ifndef __ALGO_Kalman_ATY_C
  32. #define __ALGO_Kalman_ATY_C
  33. #include "ALGO_Kalman_ATY.h"
  34. /******************************* For user *************************************/
  35. /******************************************************************************/
  36. #if !Kalman1D_TYPE // use below instead
  37. /**
  38. * @brief Kalman filter one-dimensional with A = H = 1
  39. * @param kfp kalman struct init value
  40. * @param input filter data(series)
  41. * @return data after filter
  42. * @note Origin equations
  43. * - State Equation
  44. * x(k) = A * x(k-1) + B * u(k) + w(k-1)
  45. * (if no controlled quantity then: B * u(k)=0, like detect Tem/Hum)
  46. * - Observations Equation
  47. * z(k) = H * x(k) + y(k)
  48. * - Prediction Equations
  49. * x(k|k-1) = A * x(k-1|k-1) + B * u(k)
  50. * P(k|k-1) = A * P(k-1|k-1) * A^T + Q
  51. * - Correction Equations
  52. * K(k) = P(k|k-1) * H^T * (H * P(k|k-1) * H^T + R)^(-1)
  53. * x(k|k) = x(k|k-1) + K(k) * (z(k) - H * x(k|k-1))
  54. * P(k|k) = (I - K(k) * H) * P(k|k-1)
  55. * @note Equations Note:
  56. * x and P only need to be assigned initial values, each iteration will produce new values; K does not need to be assigned an initial value
  57. * Q and R assignments can also be changed in subsequent iterations
  58. * The initial values of x and P can be arbitrarily set, and the powerful Kalman filter will immediately erase the irrdibility
  59. * But notice that the initial value of P cannot be 0, otherwise the filter will think that there is no error
  60. * The larger R is, the smoother the curve is, but the filter becomes insensitive and lags exist
  61. * (The value of Q and R can also be time-varying, can recognize jump changes, can be adaptive)
  62. * Q: process noise, Q increases, dynamic response becomes faster, convergence stability becomes worse
  63. * R: measurement noise, R increases, the dynamic response becomes slower, and the convergence stability becomes better
  64. */
  65. float ALGO_KalmanFilter1D(ALGO_Kalman1D_S* kfp, float input){
  66. // Prediction covariance:
  67. // estimated system covariance at time k
  68. // = system covariance at time k-1 + process noise covariance
  69. kfp->P = kfp->L_P + kfp->Q;
  70. // Kalman gain:
  71. // Kalman gain
  72. // = system estimated covariance at time k
  73. kfp->G = kfp->P / (kfp->P + kfp->R);
  74. // Update the optimal value:
  75. // Optimal value of state variable at time k
  76. // = predicted value of state variable + Kalman gain
  77. // * (Measured value - predicted value of state variable)
  78. // / (system estimated covariance at time k + observation noise covariance)
  79. kfp->O = kfp->O + kfp->G * (input - kfp->O);
  80. // Update the covariance:
  81. // this time the system covariance is paid to kfp->LastP for the next operation
  82. kfp->L_P = (1 - kfp->G) * kfp->P;
  83. return kfp->O;
  84. }
  85. #else
  86. /**
  87. * @brief Kalman filter one-dimensional
  88. * @param kfp kalman struct init value
  89. * @param input filter data(series)
  90. * @return data after filter
  91. * @note Origin equations
  92. * - State Equation
  93. * x(k) = A * x(k-1) + B * u(k) + w(k-1)
  94. * (if no controlled quantity then: B * u(k)=0, like detect Tem/Hum)
  95. * - Observations Equation
  96. * z(k) = H * x(k) + y(k)
  97. * - Prediction Equations
  98. * x(k|k-1) = A * x(k-1|k-1) + B * u(k)
  99. * P(k|k-1) = A * P(k-1|k-1) * A^T + Q
  100. * - Correction Equations
  101. * K(k) = P(k|k-1) * H^T * (H * P(k|k-1) * H^T + R)^(-1)
  102. * x(k|k) = x(k|k-1) + K(k) * (z(k) - H * x(k|k-1))
  103. * P(k|k) = (I - K(k) * H) * P(k|k-1)
  104. * @note Equations Note:
  105. * x and P only need to be assigned initial values, each iteration will produce new values; K does not need to be assigned an initial value
  106. * Q and R assignments can also be changed in subsequent iterations
  107. * The initial values of x and P can be arbitrarily set, and the powerful Kalman filter will immediately erase the irrdibility
  108. * But notice that the initial value of P cannot be 0, otherwise the filter will think that there is no error
  109. * The larger R is, the smoother the curve is, but the filter becomes insensitive and lags exist
  110. * (The value of Q and R can also be time-varying, can recognize jump changes, can be adaptive)
  111. * Q: process noise, Q increases, dynamic response becomes faster, convergence stability becomes worse
  112. * R: measurement noise, R increases, the dynamic response becomes slower, and the convergence stability becomes better
  113. * @note A = H = 1 in always use
  114. */
  115. float ALGO_KalmanFilter1D(ALGO_Kalman1D_S* kfp, float input){
  116. // Prediction covariance:
  117. // estimated system covariance at time k
  118. // = system covariance at time k-1 + process noise covariance
  119. kfp->X = kfp->A * kfp->X;
  120. kfp->P = kfp->A * kfp->A * kfp->P + kfp->Q;
  121. // Kalman gain:
  122. // Kalman gain
  123. // = system estimated covariance at time k
  124. kfp->G = kfp->P * kfp->H / (kfp->P * kfp->H * kfp->H + kfp->R);
  125. // Update the optimal value:
  126. // Optimal value of state variable at time k
  127. // = predicted value of state variable + Kalman gain
  128. // * (Measured value - predicted value of state variable)
  129. // / (system estimated covariance at time k + observation noise covariance)
  130. kfp->X = kfp->X + kfp->G * (input - kfp->H * kfp->X);
  131. // Update the covariance:
  132. // this time the system covariance is paid to kfp->LastP for the next operation
  133. kfp->P = (1 - kfp->G * kfp->H) * kfp->P;
  134. return kfp->X;
  135. }
  136. #endif /* 01 */
  137. #ifdef Kalman_2D
  138. /**
  139. * @brief Kalman filter two-dimensional
  140. * @param kfp kalman struct init value
  141. * @param input filter data(series)
  142. * @return data after filter
  143. * @note allways in default:
  144. * A = {{1, 0.1}, {0, 1}};
  145. * H = {1, 0};
  146. */
  147. float ALGO_KalmanFilter2D(ALGO_Kalman2D_S* kfp, float input){
  148. float temp[3] = {0.0};
  149. /* Step1: Predict */
  150. kfp->X[0] = kfp->A[0][0] * kfp->X[0] + kfp->A[0][1] * kfp->X[1];
  151. kfp->X[1] = kfp->A[1][0] * kfp->X[0] + kfp->A[1][1] * kfp->X[1];
  152. /* P(n|n-1)=A^2*P(n-1|n-1)+Q */
  153. kfp->P[0][0] = kfp->A[0][0] * kfp->P[0][0] + kfp->A[0][1] * kfp->P[1][0] + kfp->Q[0][0];
  154. kfp->P[0][1] = kfp->A[0][0] * kfp->P[0][1] + kfp->A[1][1] * kfp->P[1][1] + kfp->Q[0][1];
  155. kfp->P[1][0] = kfp->A[1][0] * kfp->P[0][0] + kfp->A[0][1] * kfp->P[1][0] + kfp->Q[1][0];
  156. // kfp->P[0][1] = kfp->A[0][0] * kfp->P[0][1] + kfp->A[1][1] * kfp->P[1][1];
  157. // kfp->P[1][0] = kfp->A[1][0] * kfp->P[0][0] + kfp->A[0][1] * kfp->P[1][0];
  158. kfp->P[1][1] = kfp->A[1][0] * kfp->P[0][1] + kfp->A[1][1] * kfp->P[1][1] + kfp->Q[1][1];
  159. /* Step2: Measurement */
  160. /* G = P * H^T * [R + H * P * H^T]^(-1), H^T means transpose. */
  161. temp[0] = kfp->P[0][0] * kfp->H[0] + kfp->P[0][1] * kfp->H[1];
  162. temp[1] = kfp->P[1][0] * kfp->H[0] + kfp->P[1][1] * kfp->H[1];
  163. temp[2] = kfp->R + kfp->H[0] * temp[0] + kfp->H[1] * temp[1];
  164. kfp->G[0] = temp[0] / temp[2];
  165. kfp->G[1] = temp[1] / temp[2];
  166. /* x(n|n) = x(n|n-1) + G(n) * [input - H(n)*x(n|n-1)]*/
  167. temp[2] = kfp->H[0] * kfp->X[0] + kfp->H[1] * kfp->X[1];
  168. kfp->X[0] = kfp->X[0] + kfp->G[0] * (input - temp[2]);
  169. kfp->X[1] = kfp->X[1] + kfp->G[1] * (input - temp[2]);
  170. /* Update @P: P(n|n) = [I - G * H] * P(n|n-1) */
  171. kfp->P[0][0] = (1 - kfp->G[0] * kfp->H[0]) * kfp->P[0][0];
  172. kfp->P[0][1] = (1 - kfp->G[0] * kfp->H[1]) * kfp->P[0][1];
  173. kfp->P[1][0] = (1 - kfp->G[1] * kfp->H[0]) * kfp->P[1][0];
  174. kfp->P[1][1] = (1 - kfp->G[1] * kfp->H[1]) * kfp->P[1][1];
  175. return kfp->X[0];
  176. }
  177. #endif /* Kalman_2D */
  178. #ifdef ALGO_Kalman_ATY_Test_ATY
  179. #if !Kalman1D_TYPE
  180. ALGO_Kalman1D_S ALGO_kfp1D = {1, 0, 0, 0, 1e-9, 1e-6};
  181. #else
  182. ALGO_Kalman1D_S ALGO_kfp1D = {0, 0, 1, 1, 1, 1e-9, 1e-6};
  183. #endif /* Kalman1D_TYPE */
  184. #ifdef Kalman_2D
  185. ALGO_Kalman2D_S ALGO_kfp2D =
  186. {
  187. {0, 0},
  188. {0, 0},
  189. {{1, 0.1}, {0, 1}},
  190. {1, 0},
  191. {{1, 0}, {0, 1}},
  192. {{1e-9, 0}, {0, 1e-9}},
  193. 10e-6
  194. };
  195. #endif /* Kalman_2D */
  196. uint16_t tempSaveOW = 0;
  197. float tempSaveO = 0;
  198. float tempSaveK = 0;
  199. float tempSaveK2 = 0;
  200. void ALGO_Kalman_Test(void){
  201. uint16_t i = 0;
  202. uint8_t testNum = 1;
  203. if(testNum == 1){
  204. ALGO_kfp1D.Q = 1e-6;
  205. ALGO_kfp1D.R = 1e-4;
  206. for(i = 0; i < 120; i++){
  207. tempSaveO = testSignalSigned[i];
  208. tempSaveK = ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalSigned[i]);
  209. #ifdef Kalman_2D
  210. tempSaveK2 = ALGO_KalmanFilter2D(&ALGO_kfp2D, testSignalSigned[i]);
  211. #endif /* Kalman_2D */
  212. printf_ATY_D("$");
  213. printf_ATY_D("%f ", testSignalSigned[i]);
  214. printf_ATY_D("%f", ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalSigned[i]));
  215. printf_ATY_D(";");
  216. }
  217. }
  218. else if(testNum == 2){
  219. ALGO_kfp1D.Q = 1e-6;
  220. ALGO_kfp1D.R = 1e-4;
  221. for(i = 0; i < 120; i++){
  222. tempSaveO = testSignalUnsigned[i];
  223. tempSaveK = ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalUnsigned[i]);
  224. #ifdef Kalman_2D
  225. tempSaveK2 = ALGO_KalmanFilter2D(&ALGO_kfp2D, testSignalUnsigned[i]);
  226. #endif /* Kalman_2D */
  227. printf_ATY_D("$");
  228. printf_ATY_D("%f ", testSignalUnsigned[i]);
  229. printf_ATY_D("%f", ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalUnsigned[i]));
  230. printf_ATY_D(";");
  231. }
  232. }
  233. else if(testNum == 3){
  234. ALGO_kfp1D.Q = 1e-9;
  235. ALGO_kfp1D.R = 1e-6;
  236. for(i = 0; i < 3000; i++){
  237. tempSaveO = (float)testSignalUint16[i];
  238. tempSaveK = ALGO_KalmanFilter1D(&ALGO_kfp1D, testSignalUint16[i]);
  239. #ifdef Kalman_2D
  240. tempSaveK2 = ALGO_KalmanFilter2D(&ALGO_kfp2D, testSignalUint16[i]);
  241. #endif /* Kalman_2D */
  242. printf_ATY_D("$");
  243. printf_ATY_D("%d ", testSignalUint16[i]);
  244. printf_ATY_D("%d", (uint16_t)ALGO_KalmanFilter1D(&ALGO_kfp1D, (float)testSignalUint16[i]));
  245. printf_ATY_D(";");
  246. }
  247. }
  248. }
  249. // debug output data format: $y1a y1b;$y2a y2b;...------------------------------
  250. // $0.732202 0.732166;$1.107485 0.923521;$0.832648 0.891278;$0.997930 0.921472;
  251. // $0.743661 0.878040;$0.928340 0.889176;$0.546396 0.818120;$0.510484 0.757106;
  252. // $0.114057 0.633303;$0.181101 0.547962;$-0.103150 0.426716;$-0.561716 0.244303;
  253. // $-0.307147 0.143145;$-0.921523 -0.051368;$-0.626582 -0.156174;$-0.817900 -0.276524;
  254. // $-0.899243 -0.389642;$-1.011869 -0.502578;$-0.948660 -0.583498;$-1.024685 -0.663502;
  255. // $-1.078591 -0.738754;$-0.854667 -0.759765;$-0.905492 -0.786177;$-0.548572 -0.743116;
  256. // $-0.737286 -0.742059;$-0.450227 -0.689175;$-1.032790 -0.751442;$-0.293712 -0.668498;
  257. // $-0.159926 -0.576342;$-0.117551 -0.493208;$0.363302 -0.338006;$0.637550 -0.161233;
  258. // $0.284187 -0.080522;$0.737519 0.067708;$0.521005 0.149846;$0.893311 0.284563;
  259. // $1.054081 0.424001;$0.525526 0.442397;$0.782144 0.503960;$1.009261 0.595521;
  260. // $0.967746 0.662969;$1.229197 0.765570;$1.179795 0.840628;$0.998553 0.869244;
  261. // $0.806697 0.857911;$0.615047 0.813903;$0.003506 0.667058;$0.023320 0.550412;
  262. // $0.510523 0.543184;$0.020320 0.448441;$-0.168222 0.336701;$-0.358753 0.210684;
  263. // $-0.424160 0.095649;$-0.492052 -0.010843;$-0.425293 -0.085942;$-0.460660 -0.153841;
  264. // $-0.712114 -0.255001;$-1.311701 -0.446476;$-0.815038 -0.513260;$-0.827395 -0.570182;
  265. // $-0.946493 -0.638370;$-0.962119 -0.697033;$-0.849309 -0.724626;$-0.733573 -0.726247;
  266. // $-0.680960 -0.718041;$-0.742870 -0.722540;$-0.529109 -0.687490;$-0.567446 -0.665738;
  267. // $-0.136456 -0.569832;$-0.199753 -0.502773;$0.169624 -0.380934;$0.231133 -0.270027;
  268. // $0.686898 -0.096631;$0.284297 -0.027606;$0.491547 0.066465;$0.766148 0.193248;
  269. // $0.808002 0.304642;$1.106872 0.450007;$1.134952 0.574120;$0.806723 0.616268;
  270. // $1.119804 0.707509;$0.931759 0.748143;$1.326805 0.852998;$0.890237 0.859745;
  271. // $0.653111 0.822303;$0.973650 0.849727;$0.903934 0.859550;$0.350950 0.767391;
  272. // $0.088230 0.644326;$0.208081 0.565278;$-0.084471 0.447543;$-0.272629 0.317047;
  273. // $-0.352162 0.195785;$-0.748851 0.024616;$-0.887943 -0.140741;$-0.736057 -0.248613;
  274. // $-0.939653 -0.373830;$-1.119212 -0.508894;$-0.944213 -0.587774;$-0.761944 -0.619334;
  275. // $-0.988381 -0.686206;$-0.681791 -0.685406;$-0.900586 -0.724397;$-1.064615 -0.786045;
  276. // $-0.843333 -0.796425;$-0.718142 -0.782240;$-0.138929 -0.665672;$-0.583088 -0.650707;
  277. // $-0.460869 -0.616308;$-0.050059 -0.513703;$0.101613 -0.402207;$0.150226 -0.302106;
  278. // $0.593740 -0.139777;$0.454790 -0.032041;$0.612092 0.084677;$0.829426 0.219626;
  279. // $0.899205 0.342766;$1.024959 0.466381;$1.159378 0.591953;$0.977459 0.661807;
  280. // <!DOCTYPE html>
  281. // <html>
  282. // <head><title>Line</title></head>
  283. // <body>
  284. // <textarea id="dataInput" style="width: 795px;" placeholder="$y1a y1b;$y2a y2b;..."
  285. // onchange="plotGraph()"></textarea><br>
  286. // <canvas id="graphCanvas" width="800" height="400"></canvas>
  287. // <script>
  288. // function parseData(input) {
  289. // const records = input.trim().split(';').filter(r => r.trim() !== '');
  290. // const s1 = [], s2 = [];
  291. // for (let r of records) {
  292. // if (!r.startsWith('$')) continue;
  293. // const vals = r.substring(1).trim().split(/\s+/);
  294. // if (vals.length !== 2) continue;
  295. // const y1 = parseFloat(vals[0]), y2 = parseFloat(vals[1]);
  296. // if (isNaN(y1) || isNaN(y2)) continue;
  297. // s1.push(y1); s2.push(y2);
  298. // }
  299. // return { s1, s2 };
  300. // }
  301. // function plotGraph() {
  302. // const { s1, s2 } = parseData(document.getElementById('dataInput').value);
  303. // if (s1.length === 0 || s2.length === 0) { alert('No valid data'); return; }
  304. // const canvas = document.getElementById('graphCanvas');
  305. // const ctx = canvas.getContext('2d');
  306. // ctx.clearRect(0, 0, canvas.width, canvas.height);
  307. // const allY = [...s1, ...s2];
  308. // let minY = Math.min(...allY), maxY = Math.max(...allY);
  309. // const margin = (maxY - minY) * 0.05 || 0.1;
  310. // minY -= margin; maxY += margin;
  311. // const n = s1.length, w = canvas.width, h = canvas.height;
  312. // function mapY(y) { return h - ((y - minY) / (maxY - minY)) * h; }
  313. // ctx.strokeStyle = '#1f77b4'; ctx.beginPath();
  314. // for (let i = 0; i < n; i++) {
  315. // const x = (i / (n - 1)) * w, y = mapY(s1[i]);
  316. // if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
  317. // }
  318. // ctx.stroke();
  319. // ctx.strokeStyle = '#ff7f0e'; ctx.beginPath();
  320. // for (let i = 0; i < n; i++) {
  321. // const x = (i / (n - 1)) * w, y = mapY(s2[i]);
  322. // if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
  323. // }
  324. // ctx.stroke();
  325. // }
  326. // </script>
  327. // </body>
  328. // </html>
  329. #endif /* ALGO_Kalman_ATY_Test_ATY */
  330. #endif /* __ALGO_Kalman_ATY_C */
  331. /******************************** End Of File *********************************/