math.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  1. // math.js
  2. // Linear-algebra helpers + sample averaging.
  3. // Pure functions; no DOM; no side effects.
  4. // ---- Sample averaging (V2) ----
  5. // Averages all the per-frame features collected during calibration. Old samples
  6. // without ear/pitch/yaw simply contribute 0 to the corresponding sums (we
  7. // branch on the field being defined), so the function degrades gracefully if
  8. // it's ever called on a partially-populated sample batch.
  9. export function averageSamples(samples) {
  10. if (!samples.length) {
  11. return { ratioX: 0.5, ratioY: 0.5, ear: 0, pitch: 0, yaw: 0 };
  12. }
  13. let sx = 0, sy = 0;
  14. let eSum = 0, eN = 0;
  15. let pSum = 0, pN = 0;
  16. let wSum = 0, wN = 0;
  17. for (let i = 0; i < samples.length; i++) {
  18. const s = samples[i];
  19. sx += s.ratioX;
  20. sy += s.ratioY;
  21. if (s.ear !== undefined && s.ear !== null) { eSum += s.ear; eN++; }
  22. if (s.pitch !== undefined && s.pitch !== null) { pSum += s.pitch; pN++; }
  23. if (s.yaw !== undefined && s.yaw !== null) { wSum += s.yaw; wN++; }
  24. }
  25. const n = samples.length;
  26. return {
  27. ratioX: sx / n,
  28. ratioY: sy / n,
  29. ear: eN ? eSum / eN : 0,
  30. pitch: pN ? pSum / pN : 0,
  31. yaw: wN ? wSum / wN : 0
  32. };
  33. }
  34. // ---- NxN linear solver (Gaussian elimination with partial pivoting) ----
  35. // Replaces the old Cramer's-rule 6x6 solver when we need a 9x9 (or any other
  36. // size) normal equation. Cramer's is O(n!) and becomes both slow and
  37. // numerically unstable past ~6x6, so we switch to LU-with-pivoting here.
  38. //
  39. // A is an n×n matrix (array of n row-arrays of length n).
  40. // b is an n-vector.
  41. // Returns the n-vector x such that A·x = b, or null if A is singular
  42. // (rank-deficient to machine precision, |pivot| < 1e-12).
  43. export function solveNxN(n, A, b) {
  44. // Build the augmented [A|b] matrix in row-major form.
  45. const M = new Array(n);
  46. for (let i = 0; i < n; i++) {
  47. const row = new Array(n + 1);
  48. for (let j = 0; j < n; j++) row[j] = A[i][j];
  49. row[n] = b[i];
  50. M[i] = row;
  51. }
  52. // Forward elimination.
  53. for (let k = 0; k < n; k++) {
  54. // Partial pivoting: pick the row with the largest |M[i][k]| for i >= k.
  55. let maxVal = Math.abs(M[k][k]);
  56. let maxRow = k;
  57. for (let i = k + 1; i < n; i++) {
  58. const v = Math.abs(M[i][k]);
  59. if (v > maxVal) { maxVal = v; maxRow = i; }
  60. }
  61. if (maxVal < 1e-12) return null; // singular
  62. if (maxRow !== k) { // swap rows
  63. const tmp = M[k]; M[k] = M[maxRow]; M[maxRow] = tmp;
  64. }
  65. // Eliminate below the pivot.
  66. for (let i = k + 1; i < n; i++) {
  67. const factor = M[i][k] / M[k][k];
  68. if (factor === 0) continue;
  69. for (let j = k; j <= n; j++) {
  70. M[i][j] -= factor * M[k][j];
  71. }
  72. }
  73. }
  74. // Back substitution.
  75. const x = new Array(n);
  76. for (let i = n - 1; i >= 0; i--) {
  77. let sum = M[i][n];
  78. for (let j = i + 1; j < n; j++) sum -= M[i][j] * x[j];
  79. x[i] = sum / M[i][i];
  80. }
  81. return x;
  82. }
  83. // ============================================================
  84. // Old 6-dim helpers (kept for back-compat / regression testing)
  85. // ============================================================
  86. // Solve a 3×3 linear system A x = b via Cramer's rule.
  87. // Returns [x0, x1, x2] or null if A is singular.
  88. export function solve3x3(A, b) {
  89. const det = (
  90. A[0][0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
  91. A[0][1] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
  92. A[0][2] * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
  93. );
  94. if (Math.abs(det) < 1e-9) return null;
  95. const det0 = (
  96. b[0] * (A[1][1] * A[2][2] - A[1][2] * A[2][1]) -
  97. A[0][1] * (b[1] * A[2][2] - A[1][2] * b[2]) +
  98. A[0][2] * (b[1] * A[2][1] - A[1][1] * b[2])
  99. );
  100. const det1 = (
  101. A[0][0] * (b[1] * A[2][2] - A[1][2] * b[2]) -
  102. b[0] * (A[1][0] * A[2][2] - A[1][2] * A[2][0]) +
  103. A[0][2] * (A[1][0] * b[2] - b[1] * A[2][0])
  104. );
  105. const det2 = (
  106. A[0][0] * (A[1][1] * b[2] - b[1] * A[2][1]) -
  107. A[0][1] * (A[1][0] * b[2] - b[1] * A[2][0]) +
  108. b[0] * (A[1][0] * A[2][1] - A[1][1] * A[2][0])
  109. );
  110. return [det0 / det, det1 / det, det2 / det];
  111. }
  112. // 6x6 Cramer's rule: solve Ax=b where A is 6x6, b is 6x1
  113. // A is passed as array of 6 rows, each row is [a0..a5]
  114. export function solve6x6(A, b) {
  115. function det6(m) {
  116. // Compute 6x6 determinant via cofactor expansion along first row
  117. let d = 0;
  118. for (let j = 0; j < 6; j++) {
  119. const minor = [];
  120. for (let i = 1; i < 6; i++) {
  121. const row = [];
  122. for (let k = 0; k < 6; k++) {
  123. if (k !== j) row.push(m[i][k]);
  124. }
  125. minor.push(row);
  126. }
  127. const sign = (j % 2 === 0) ? 1 : -1;
  128. d += sign * m[0][j] * det5(minor);
  129. }
  130. return d;
  131. }
  132. function det5(m) {
  133. let d = 0;
  134. for (let j = 0; j < 5; j++) {
  135. const minor = [];
  136. for (let i = 1; i < 5; i++) {
  137. const row = [];
  138. for (let k = 0; k < 5; k++) {
  139. if (k !== j) row.push(m[i][k]);
  140. }
  141. minor.push(row);
  142. }
  143. const sign = (j % 2 === 0) ? 1 : -1;
  144. d += sign * m[0][j] * det4(minor);
  145. }
  146. return d;
  147. }
  148. function det4(m) {
  149. // 4x4 determinant via cofactor expansion
  150. let d = 0;
  151. for (let j = 0; j < 4; j++) {
  152. const minor = [];
  153. for (let i = 1; i < 4; i++) {
  154. const row = [];
  155. for (let k = 0; k < 4; k++) {
  156. if (k !== j) row.push(m[i][k]);
  157. }
  158. minor.push(row);
  159. }
  160. const sign = (j % 2 === 0) ? 1 : -1;
  161. d += sign * m[0][j] * det3(minor);
  162. }
  163. return d;
  164. }
  165. function det3(m) {
  166. return m[0][0]*(m[1][1]*m[2][2]-m[1][2]*m[2][1])
  167. - m[0][1]*(m[1][0]*m[2][2]-m[1][2]*m[2][0])
  168. + m[0][2]*(m[1][0]*m[2][1]-m[1][1]*m[2][0]);
  169. }
  170. const D = det6(A);
  171. if (Math.abs(D) < 1e-12) return null; // singular
  172. const x = [];
  173. for (let j = 0; j < 6; j++) {
  174. const Aj = A.map((row, i) => {
  175. const r = row.slice();
  176. r[j] = b[i];
  177. return r;
  178. });
  179. x.push(det6(Aj) / D);
  180. }
  181. return x;
  182. }
  183. // Build 6-dim polynomial design row from iris ratios
  184. export function buildPolyFeatures(rX, rY) {
  185. return [1, rX, rY, rX*rX, rY*rY, rX*rY];
  186. }
  187. // Build the design matrix for [a0, a1, …, a5] with rows [1, rX, rY, rX², rY², rX*rY].
  188. export function buildDesignMatrix(points) {
  189. const M = [];
  190. for (let i = 0; i < points.length; i++) {
  191. M.push(buildPolyFeatures(points[i].ratioX, points[i].ratioY));
  192. }
  193. return M;
  194. }
  195. // Ordinary least squares for y = X * beta. Returns beta = [b0, …, b5]
  196. // (we use Cramer's rule on X^T X and X^T y — small, dense, exact).
  197. export function olsFit(X, y) {
  198. const n = X.length;
  199. // X^T X (6x6)
  200. const A = [[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,0]];
  201. // X^T y (6x1)
  202. const b = [0, 0, 0, 0, 0, 0];
  203. for (let i = 0; i < n; i++) {
  204. const xi = X[i];
  205. for (let r = 0; r < 6; r++) {
  206. for (let c = 0; c < 6; c++) A[r][c] += xi[r] * xi[c];
  207. b[r] += xi[r] * y[i];
  208. }
  209. }
  210. return solve6x6(A, b);
  211. }
  212. // ============================================================
  213. // V2 (9-dim) helpers: [1, rX, rY, ear, pitch, yaw, rX², rY², rX*rY]
  214. // ============================================================
  215. // The V2 feature layout. Head-pose features (ear, pitch, yaw) enter
  216. // linearly; the polynomial cross-terms (rX², rY², rX*rY) only involve
  217. // the iris ratios, which is what the literature converges on (eye-contour
  218. // + iris is dominant, with head pose as an auxiliary).
  219. export const N_FEATURES_V2 = 9;
  220. // Build one 9-dim design row from a (rX, rY, ear, pitch, yaw) sample.
  221. export function buildPolyFeaturesV2(rX, rY, ear, pitch, yaw) {
  222. return [1, rX, rY, ear, pitch, yaw, rX*rX, rY*rY, rX*rY];
  223. }
  224. // Build a 9-dim design matrix from a list of points that carry the V2 features.
  225. // `points` is expected to be [{ ratioX, ratioY, ear, pitch, yaw }, ...].
  226. export function buildDesignMatrixV2(points) {
  227. const M = [];
  228. for (let i = 0; i < points.length; i++) {
  229. const p = points[i];
  230. M.push(buildPolyFeaturesV2(
  231. p.ratioX, p.ratioY,
  232. p.ear != null ? p.ear : 0,
  233. p.pitch != null ? p.pitch : 0,
  234. p.yaw != null ? p.yaw : 0
  235. ));
  236. }
  237. return M;
  238. }
  239. // Ordinary least squares for an arbitrary-dim design matrix.
  240. // X is m × nFeatures (m >= nFeatures), y is m × 1.
  241. // Solves (X^T X) beta = X^T y via Gaussian elimination with partial pivoting.
  242. export function olsFitV2(X, y, nFeatures) {
  243. const n = X.length;
  244. // X^T X (nFeatures x nFeatures)
  245. const A = new Array(nFeatures);
  246. for (let r = 0; r < nFeatures; r++) A[r] = new Array(nFeatures).fill(0);
  247. // X^T y (nFeatures x 1)
  248. const b = new Array(nFeatures).fill(0);
  249. for (let i = 0; i < n; i++) {
  250. const xi = X[i];
  251. for (let r = 0; r < nFeatures; r++) {
  252. for (let c = 0; c < nFeatures; c++) A[r][c] += xi[r] * xi[c];
  253. b[r] += xi[r] * y[i];
  254. }
  255. }
  256. return solveNxN(nFeatures, A, b);
  257. }