@danielsimonjr/mathts-functions 0.69.2 → 0.70.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/README.md +66 -1
  2. package/dist/algebra/decomposition/lup.d.ts.map +1 -1
  3. package/dist/algebra/decomposition/qr.d.ts.map +1 -1
  4. package/dist/algebra/simplify/util.d.ts.map +1 -1
  5. package/dist/algebra/simplifyConstant.d.ts +3 -4
  6. package/dist/algebra/simplifyConstant.d.ts.map +1 -1
  7. package/dist/algebra/solver/lsolve.d.ts.map +1 -1
  8. package/dist/algebra/solver/usolve.d.ts.map +1 -1
  9. package/dist/arithmetic/ceil.d.ts.map +1 -1
  10. package/dist/arithmetic/fix.d.ts.map +1 -1
  11. package/dist/arithmetic/floor.d.ts.map +1 -1
  12. package/dist/arithmetic/norm.d.ts.map +1 -1
  13. package/dist/arithmetic/round.d.ts.map +1 -1
  14. package/dist/arithmetic/sign.d.ts +2 -2
  15. package/dist/arithmetic/sign.d.ts.map +1 -1
  16. package/dist/arithmetic/snap-to-round.d.ts +36 -0
  17. package/dist/arithmetic/snap-to-round.d.ts.map +1 -0
  18. package/dist/arithmetic/xgcd.d.ts +6 -6
  19. package/dist/arithmetic/xgcd.d.ts.map +1 -1
  20. package/dist/cas/layer3.d.ts.map +1 -1
  21. package/dist/cas/rational-integrate.d.ts.map +1 -1
  22. package/dist/cas/render-coeff-times.d.ts +7 -0
  23. package/dist/cas/render-coeff-times.d.ts.map +1 -0
  24. package/dist/cas-integration.d.ts.map +1 -1
  25. package/dist/config-api.d.ts +47 -5
  26. package/dist/config-api.d.ts.map +1 -1
  27. package/dist/descriptive-stats.d.ts +4 -0
  28. package/dist/descriptive-stats.d.ts.map +1 -1
  29. package/dist/factories/index.d.ts +3 -0
  30. package/dist/factories/index.d.ts.map +1 -1
  31. package/dist/factories/scope.d.ts +8 -0
  32. package/dist/factories/scope.d.ts.map +1 -1
  33. package/dist/fit-scalar.d.ts +49 -0
  34. package/dist/fit-scalar.d.ts.map +1 -0
  35. package/dist/front-export.d.ts +81 -0
  36. package/dist/front-export.d.ts.map +1 -0
  37. package/dist/geometry/alpha-shape.d.ts.map +1 -1
  38. package/dist/geometry/circumcircle.d.ts +16 -0
  39. package/dist/geometry/circumcircle.d.ts.map +1 -0
  40. package/dist/geometry/geometry-extra.d.ts.map +1 -1
  41. package/dist/geometry/voronoi.d.ts.map +1 -1
  42. package/dist/gpu/elementwise-gpu.d.ts +2 -0
  43. package/dist/gpu/elementwise-gpu.d.ts.map +1 -1
  44. package/dist/index.d.ts +19 -2
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +24998 -25385
  47. package/dist/matrix/column.d.ts.map +1 -1
  48. package/dist/matrix/complex-to-interleaved.d.ts +7 -0
  49. package/dist/matrix/complex-to-interleaved.d.ts.map +1 -0
  50. package/dist/matrix/fft.d.ts.map +1 -1
  51. package/dist/matrix/from-vectors.d.ts +45 -0
  52. package/dist/matrix/from-vectors.d.ts.map +1 -0
  53. package/dist/matrix/ifft.d.ts.map +1 -1
  54. package/dist/matrix/mapSlices.d.ts.map +1 -1
  55. package/dist/matrix/matrixFromColumns.d.ts.map +1 -1
  56. package/dist/matrix/matrixFromRows.d.ts.map +1 -1
  57. package/dist/matrix/native-accel.d.ts.map +1 -1
  58. package/dist/matrix/partitionSelect.d.ts +1 -0
  59. package/dist/matrix/partitionSelect.d.ts.map +1 -1
  60. package/dist/matrix/row.d.ts.map +1 -1
  61. package/dist/matrix/slice-2d.d.ts +16 -0
  62. package/dist/matrix/slice-2d.d.ts.map +1 -0
  63. package/dist/matrix/sort.d.ts +1 -1
  64. package/dist/matrix/sort.d.ts.map +1 -1
  65. package/dist/matrix/sparse-csc-tail.d.ts +21 -0
  66. package/dist/matrix/sparse-csc-tail.d.ts.map +1 -0
  67. package/dist/ml/dbscan-knn.d.ts +6 -0
  68. package/dist/ml/dbscan-knn.d.ts.map +1 -1
  69. package/dist/ml/ols.d.ts.map +1 -1
  70. package/dist/ml/regularized-regression.d.ts.map +1 -1
  71. package/dist/numbertheory/extra.d.ts.map +1 -1
  72. package/dist/numeric/bfgs.d.ts.map +1 -1
  73. package/dist/numeric/control-equations.d.ts +0 -47
  74. package/dist/numeric/control-equations.d.ts.map +1 -1
  75. package/dist/numeric/eigsh.d.ts.map +1 -1
  76. package/dist/numeric/fsolve.d.ts.map +1 -1
  77. package/dist/numeric/hermite.d.ts +22 -0
  78. package/dist/numeric/hermite.d.ts.map +1 -0
  79. package/dist/numeric/krylov.d.ts.map +1 -1
  80. package/dist/numeric/numeric-jacobian.d.ts +65 -7
  81. package/dist/numeric/numeric-jacobian.d.ts.map +1 -1
  82. package/dist/numeric/open-root-finders.d.ts.map +1 -1
  83. package/dist/numeric/solveDAE.d.ts.map +1 -1
  84. package/dist/numeric/solveDDE.d.ts.map +1 -1
  85. package/dist/numeric/solveODE.d.ts.map +1 -1
  86. package/dist/numeric/svds.d.ts.map +1 -1
  87. package/dist/numeric-equivalence.d.ts +110 -0
  88. package/dist/numeric-equivalence.d.ts.map +1 -0
  89. package/dist/numeric-extra.d.ts.map +1 -1
  90. package/dist/optimization-extra.d.ts +33 -10
  91. package/dist/optimization-extra.d.ts.map +1 -1
  92. package/dist/pareto-front.d.ts +165 -0
  93. package/dist/pareto-front.d.ts.map +1 -0
  94. package/dist/plain/number/probability.d.ts +9 -3
  95. package/dist/plain/number/probability.d.ts.map +1 -1
  96. package/dist/probability/bigint-binomial.d.ts +34 -0
  97. package/dist/probability/bigint-binomial.d.ts.map +1 -0
  98. package/dist/probability/combinations.d.ts.map +1 -1
  99. package/dist/probability/combinationsWithRep.d.ts.map +1 -1
  100. package/dist/scalar-batch-parallel.d.ts +71 -0
  101. package/dist/scalar-batch-parallel.d.ts.map +1 -0
  102. package/dist/scalar-batch-task-CZd6LPg9.js +2587 -0
  103. package/dist/scalar-batch-task.d.ts +40 -0
  104. package/dist/scalar-batch-task.d.ts.map +1 -0
  105. package/dist/scalar-batch.worker.js +34 -0
  106. package/dist/scalar-compile.d.ts +227 -0
  107. package/dist/scalar-compile.d.ts.map +1 -0
  108. package/dist/scalar-dimension.d.ts +54 -0
  109. package/dist/scalar-dimension.d.ts.map +1 -0
  110. package/dist/scalar-eval.d.ts +7 -0
  111. package/dist/scalar-eval.d.ts.map +1 -1
  112. package/dist/scalar-mutate.d.ts +70 -0
  113. package/dist/scalar-mutate.d.ts.map +1 -0
  114. package/dist/scalar-node-bridge.d.ts +30 -0
  115. package/dist/scalar-node-bridge.d.ts.map +1 -0
  116. package/dist/scalar-search.d.ts +176 -0
  117. package/dist/scalar-search.d.ts.map +1 -0
  118. package/dist/set/flatten-pair.d.ts +16 -0
  119. package/dist/set/flatten-pair.d.ts.map +1 -0
  120. package/dist/set/setSymDifference.d.ts.map +1 -1
  121. package/dist/set/setUnion.d.ts.map +1 -1
  122. package/dist/signal-filter-extra.d.ts.map +1 -1
  123. package/dist/special/niche.d.ts.map +1 -1
  124. package/dist/statistics/extreme.d.ts +23 -0
  125. package/dist/statistics/extreme.d.ts.map +1 -0
  126. package/dist/statistics/max.d.ts.map +1 -1
  127. package/dist/statistics/median.d.ts +1 -1
  128. package/dist/statistics/median.d.ts.map +1 -1
  129. package/dist/statistics/min.d.ts.map +1 -1
  130. package/dist/statistics/prod.d.ts.map +1 -1
  131. package/dist/stats/inference-extra2.d.ts.map +1 -1
  132. package/dist/string/print.d.ts.map +1 -1
  133. package/dist/type/local/Decimal.d.ts +0 -3
  134. package/dist/type/local/Decimal.d.ts.map +1 -1
  135. package/dist/type/matrix/ImmutableDenseMatrix.d.ts +10 -0
  136. package/dist/type/matrix/ImmutableDenseMatrix.d.ts.map +1 -1
  137. package/dist/type/matrix/MatrixIndex.d.ts +22 -1
  138. package/dist/type/matrix/MatrixIndex.d.ts.map +1 -1
  139. package/dist/type/matrix/utils/matAlgo13xDD.d.ts.map +1 -1
  140. package/dist/type/matrix/utils/matAlgo14xDs.d.ts.map +1 -1
  141. package/dist/type/matrix/utils/matrixAlgorithmSuite.d.ts.map +1 -1
  142. package/dist/typed/aggregate-restart.d.ts +14 -0
  143. package/dist/typed/aggregate-restart.d.ts.map +1 -0
  144. package/dist/typed/algebra.d.ts +4 -0
  145. package/dist/typed/algebra.d.ts.map +1 -1
  146. package/dist/typed/arithmetic.d.ts.map +1 -1
  147. package/dist/typed/cas.d.ts +2 -1
  148. package/dist/typed/cas.d.ts.map +1 -1
  149. package/dist/typed/centrality-restarts.d.ts +13 -0
  150. package/dist/typed/centrality-restarts.d.ts.map +1 -0
  151. package/dist/typed/combinatorics.d.ts.map +1 -1
  152. package/dist/typed/dist-objects.d.ts.map +1 -1
  153. package/dist/typed/distributions.d.ts +8 -13
  154. package/dist/typed/distributions.d.ts.map +1 -1
  155. package/dist/typed/euclid.d.ts +6 -0
  156. package/dist/typed/euclid.d.ts.map +1 -0
  157. package/dist/typed/factorization/finite-field.d.ts.map +1 -1
  158. package/dist/typed/factorization/index.d.ts.map +1 -1
  159. package/dist/typed/factorization/integer-poly.d.ts +7 -0
  160. package/dist/typed/factorization/integer-poly.d.ts.map +1 -1
  161. package/dist/typed/factorization/kronecker-factor.d.ts.map +1 -1
  162. package/dist/typed/factorization/render-univariate.d.ts +11 -0
  163. package/dist/typed/factorization/render-univariate.d.ts.map +1 -0
  164. package/dist/typed/factorization/zassenhaus.d.ts +9 -0
  165. package/dist/typed/factorization/zassenhaus.d.ts.map +1 -1
  166. package/dist/typed/fused.d.ts.map +1 -1
  167. package/dist/typed/geometry.d.ts +2 -2
  168. package/dist/typed/geometry.d.ts.map +1 -1
  169. package/dist/typed/graph.d.ts +2 -7
  170. package/dist/typed/graph.d.ts.map +1 -1
  171. package/dist/typed/hypothesis.d.ts.map +1 -1
  172. package/dist/typed/index.d.ts +1 -0
  173. package/dist/typed/index.d.ts.map +1 -1
  174. package/dist/typed/interpolation.d.ts +6 -7
  175. package/dist/typed/interpolation.d.ts.map +1 -1
  176. package/dist/typed/matrix-ops.d.ts.map +1 -1
  177. package/dist/typed/normal-equations-solve.d.ts +8 -0
  178. package/dist/typed/normal-equations-solve.d.ts.map +1 -0
  179. package/dist/typed/numeric.d.ts +5 -1
  180. package/dist/typed/numeric.d.ts.map +1 -1
  181. package/dist/typed/parallel-map.d.ts +11 -0
  182. package/dist/typed/parallel-map.d.ts.map +1 -1
  183. package/dist/typed/polynomial-ideal.d.ts +6 -0
  184. package/dist/typed/polynomial-ideal.d.ts.map +1 -1
  185. package/dist/typed/set.d.ts.map +1 -1
  186. package/dist/typed/signal.d.ts +6 -6
  187. package/dist/typed/signal.d.ts.map +1 -1
  188. package/dist/typed/special.d.ts +22 -26
  189. package/dist/typed/special.d.ts.map +1 -1
  190. package/dist/typed/statistics.d.ts +19 -2
  191. package/dist/typed/statistics.d.ts.map +1 -1
  192. package/dist/typed/string-derivative.d.ts +19 -0
  193. package/dist/typed/string-derivative.d.ts.map +1 -0
  194. package/dist/typed/string.d.ts +3 -3
  195. package/dist/typed/string.d.ts.map +1 -1
  196. package/dist/typed/unit.d.ts.map +1 -1
  197. package/dist/utils/isPrime.d.ts +15 -0
  198. package/dist/utils/isPrime.d.ts.map +1 -1
  199. package/dist/utils/print.d.ts +5 -0
  200. package/dist/utils/print.d.ts.map +1 -1
  201. package/dist/utils/typed-impl.d.ts +11 -0
  202. package/dist/utils/typed-impl.d.ts.map +1 -0
  203. package/dist/wasm/WasmLoader.d.ts +3 -21
  204. package/dist/wasm/WasmLoader.d.ts.map +1 -1
  205. package/dist/wasm/bridges/common.d.ts +18 -2
  206. package/dist/wasm/bridges/common.d.ts.map +1 -1
  207. package/dist/wasm/mathts-as.wasm +0 -0
  208. package/dist/wasm/poly/wasm-bridge.d.ts +11 -0
  209. package/dist/wasm/poly/wasm-bridge.d.ts.map +1 -1
  210. package/dist/wasm/sort/wasm-bridge.d.ts +0 -10
  211. package/dist/wasm/sort/wasm-bridge.d.ts.map +1 -1
  212. package/dist/wasm/special/scalars.d.ts +49 -0
  213. package/dist/wasm/special/scalars.d.ts.map +1 -1
  214. package/dist/wasm/special/wasm-bridge.d.ts +11 -12
  215. package/dist/wasm/special/wasm-bridge.d.ts.map +1 -1
  216. package/dist/wasm/wasm-manifest.json +1 -1
  217. package/package.json +8 -8
  218. package/types/index.d.ts +1 -1
  219. package/dist/wasm/integrity.d.ts +0 -16
  220. package/dist/wasm/integrity.d.ts.map +0 -1
@@ -0,0 +1,2587 @@
1
+ import { BigNumber, Complex, DUAL_UNARY_RULES, Dual, Fraction, equal, fix, mathTyped, neumaierSum, norm2, pairwiseDot, pairwiseSum, pow, round, sumSquaredDeviations } from "@danielsimonjr/mathts-core";
2
+ import { DenseMatrix, backendManager, singularValues } from "@danielsimonjr/mathts-matrix";
3
+ import { computePool } from "@danielsimonjr/mathts-parallel";
4
+ import { WasmModuleLoader, allocAsHeader, defaultWasmLocation, resolvePackagedWasm } from "@danielsimonjr/mathts-core/internal";
5
+ import { ScalarBuildError, createScalarBuilder } from "@danielsimonjr/mathts-expression";
6
+ //#region src/typed/euclid.ts
7
+ function euclidSnap(a, b, snap) {
8
+ a = Math.abs(snap(a));
9
+ b = Math.abs(snap(b));
10
+ while (b !== 0) {
11
+ const t = b;
12
+ b = a % b;
13
+ a = t;
14
+ }
15
+ return a;
16
+ }
17
+ //#endregion
18
+ //#region src/factories/matrix-bridge.ts
19
+ backendManager.initialize().catch(() => {});
20
+ function matrixIndexSelectors(index) {
21
+ const nDims = index.size().length;
22
+ const out = [];
23
+ for (let d = 0; d < nDims; d++) {
24
+ const sel = index.dimension(d);
25
+ if (typeof sel === "number") out.push([sel]);
26
+ else if (sel && typeof sel.toArray === "function") out.push(sel.toArray());
27
+ else out.push([Number(sel)]);
28
+ }
29
+ return out;
30
+ }
31
+ function _adaptCallbackArity(callback) {
32
+ const t = mathTyped;
33
+ if (t.isTypedFunction(callback)) {
34
+ let arity;
35
+ return (...args) => {
36
+ if (arity === void 0) {
37
+ for (let k = args.length; k >= 1; k--) if (t.resolve(callback, args.slice(0, k))) {
38
+ arity = k;
39
+ break;
40
+ }
41
+ if (arity === void 0) arity = args.length;
42
+ }
43
+ return callback(...args.slice(0, arity));
44
+ };
45
+ }
46
+ const declared = callback.length;
47
+ if (declared >= 1 && declared < 3) return (...args) => callback(...args.slice(0, declared));
48
+ return callback;
49
+ }
50
+ var MathJSDenseMatrix = class MathJSDenseMatrix {
51
+ _data;
52
+ _size;
53
+ _datatype;
54
+ constructor(data) {
55
+ if (!data) {
56
+ this._data = [];
57
+ this._size = [0, 0];
58
+ } else if (Array.isArray(data)) {
59
+ this._data = data;
60
+ this._size = inferSize(data);
61
+ } else {
62
+ this._data = data.data;
63
+ this._size = data.size;
64
+ }
65
+ }
66
+ get rows() {
67
+ return this._size[0] ?? 0;
68
+ }
69
+ get cols() {
70
+ return this._size[1] ?? 0;
71
+ }
72
+ storage() {
73
+ return "dense";
74
+ }
75
+ datatype() {
76
+ return this._datatype;
77
+ }
78
+ valueOf() {
79
+ return this._data;
80
+ }
81
+ size() {
82
+ return [...this._size];
83
+ }
84
+ toArray() {
85
+ if (this._size.length === 1) return [...this._data];
86
+ return this._data.map((row) => [...row]);
87
+ }
88
+ toJSON() {
89
+ return {
90
+ mathjs: "DenseMatrix",
91
+ data: this._data,
92
+ size: this._size
93
+ };
94
+ }
95
+ create(data, datatype) {
96
+ const m = new MathJSDenseMatrix(data);
97
+ m._datatype = datatype;
98
+ return m;
99
+ }
100
+ createDenseMatrix(opts) {
101
+ const m = new MathJSDenseMatrix(opts.data);
102
+ m._size = opts.size;
103
+ m._datatype = opts.datatype;
104
+ return m;
105
+ }
106
+ map(callback) {
107
+ const cb = _adaptCallbackArity(callback);
108
+ if (this._size.length === 1) {
109
+ const flat = this._data.map((val, i) => cb(val, [i], this));
110
+ return new MathJSDenseMatrix({
111
+ data: flat,
112
+ size: [...this._size]
113
+ });
114
+ }
115
+ const result = this._data.map((row, i) => row.map((val, j) => cb(val, [i, j], this)));
116
+ return new MathJSDenseMatrix(result);
117
+ }
118
+ forEach(callback) {
119
+ const cb = _adaptCallbackArity(callback);
120
+ if (this._size.length === 1) {
121
+ this._data.forEach((val, i) => cb(val, [i], this));
122
+ return;
123
+ }
124
+ this._data.forEach((row, i) => {
125
+ row.forEach((val, j) => cb(val, [i, j], this));
126
+ });
127
+ }
128
+ get(indexOrRow, col) {
129
+ const row = Array.isArray(indexOrRow) ? indexOrRow[0] : indexOrRow;
130
+ if (this._size.length === 1) return this._data[row];
131
+ const j = Array.isArray(indexOrRow) ? indexOrRow[1] : col;
132
+ return this._data[row][j];
133
+ }
134
+ set(index, value, _defaultValue) {
135
+ if (this._size.length === 1) this._data[index[0]] = value;
136
+ else this._data[index[0]][index[1]] = value;
137
+ return this;
138
+ }
139
+ subset(index, replacement, defaultValue) {
140
+ if (Array.isArray(index)) return replacement === void 0 ? this.get(index) : this.set(index, replacement, defaultValue);
141
+ const dims = matrixIndexSelectors(index);
142
+ return replacement === void 0 ? this._getSubset(index, dims) : this._setSubset(index, dims, replacement);
143
+ }
144
+ _getSubset(index, dims) {
145
+ if (index.isScalar()) return dims.length === 1 ? this._data[dims[0][0]] : this._data[dims[0][0]][dims[1][0]];
146
+ if (dims.length === 1) {
147
+ const picked = dims[0].map((i) => this._data[i]);
148
+ const m = new MathJSDenseMatrix(picked);
149
+ m._size = [dims[0].length];
150
+ return m;
151
+ }
152
+ const [rowSel, colSel] = dims;
153
+ return new MathJSDenseMatrix(rowSel.map((i) => colSel.map((j) => this._data[i][j])));
154
+ }
155
+ _setSubset(index, dims, replacement) {
156
+ if (index.isScalar()) {
157
+ if (dims.length === 1) this._data[dims[0][0]] = replacement;
158
+ else this._data[dims[0][0]][dims[1][0]] = replacement;
159
+ return this;
160
+ }
161
+ const rep = replacement.toArray ? replacement.toArray() : replacement;
162
+ const [rowSel, colSel] = dims.length === 2 ? dims : [dims[0], [0]];
163
+ for (let ri = 0; ri < rowSel.length; ri++) for (let ci = 0; ci < colSel.length; ci++) {
164
+ const row = rep[ri];
165
+ const v = Array.isArray(row) ? row[ci] : row;
166
+ this._data[rowSel[ri]][colSel[ci]] = v;
167
+ }
168
+ return this;
169
+ }
170
+ clone() {
171
+ const copy = this._size.length === 1 ? [...this._data] : this._data.map((row) => [...row]);
172
+ const m = new MathJSDenseMatrix(copy);
173
+ m._size = [...this._size];
174
+ m._datatype = this._datatype;
175
+ return m;
176
+ }
177
+ resize(newSize, defaultValue) {
178
+ const fill = defaultValue ?? 0;
179
+ if (newSize.length === 1) {
180
+ const len = newSize[0];
181
+ const flat = [];
182
+ const oldData = this._data;
183
+ for (let i = 0; i < len; i++) flat.push(i < (this._size[0] ?? 0) ? oldData[i] ?? fill : fill);
184
+ this._data = flat;
185
+ this._size = [len];
186
+ return this;
187
+ }
188
+ const [rows, cols] = newSize;
189
+ const data = [];
190
+ const oldRows = this._size[0] ?? 0;
191
+ const oldCols = this._size[1] ?? 0;
192
+ for (let i = 0; i < rows; i++) {
193
+ const row = [];
194
+ for (let j = 0; j < cols; j++) row.push(i < oldRows && j < oldCols && this._data[i] ? this._data[i][j] ?? fill : fill);
195
+ data.push(row);
196
+ }
197
+ this._data = data;
198
+ this._size = [rows, cols];
199
+ return this;
200
+ }
201
+ reshape(newSize) {
202
+ const flat = [];
203
+ for (const row of this._data) for (const val of row) flat.push(val);
204
+ const [rows, cols] = newSize;
205
+ const data = [];
206
+ for (let i = 0; i < rows; i++) {
207
+ const row = [];
208
+ for (let j = 0; j < cols; j++) row.push(flat[i * cols + j] ?? 0);
209
+ data.push(row);
210
+ }
211
+ return new MathJSDenseMatrix({
212
+ data,
213
+ size: [rows, cols]
214
+ });
215
+ }
216
+ diagonal(k = 0) {
217
+ const [rows, cols] = this._size;
218
+ const kRow = k < 0 ? -k : 0;
219
+ const kCol = k > 0 ? k : 0;
220
+ const diagLen = Math.min(rows - kRow, cols - kCol);
221
+ const values = [];
222
+ for (let i = 0; i < diagLen; i++) values.push(this._data[kRow + i][kCol + i]);
223
+ const m = new MathJSDenseMatrix();
224
+ m._data = values;
225
+ m._size = [diagLen];
226
+ return m;
227
+ }
228
+ getDataType() {
229
+ return this._datatype ?? "number";
230
+ }
231
+ multiply(other) {
232
+ const result = backendManager.multiply(this.toNative(), other.toNative());
233
+ return MathJSDenseMatrix.fromNative(result);
234
+ }
235
+ transpose() {
236
+ const result = backendManager.transpose(this.toNative());
237
+ return MathJSDenseMatrix.fromNative(result);
238
+ }
239
+ toNative() {
240
+ return DenseMatrix.fromArray(this._data);
241
+ }
242
+ static fromNative(dm) {
243
+ return new MathJSDenseMatrix(dm.toArray());
244
+ }
245
+ static _swapRows(i, j, data) {
246
+ const vi = data[i];
247
+ data[i] = data[j];
248
+ data[j] = vi;
249
+ }
250
+ static diagonal(size, value, k = 0, defaultValue = 0) {
251
+ const [rows, cols] = size;
252
+ const data = Array.from({ length: rows }, () => new Array(cols).fill(defaultValue));
253
+ const kRow = k < 0 ? -k : 0;
254
+ const kCol = k > 0 ? k : 0;
255
+ const diagLen = Math.min(rows - kRow, cols - kCol);
256
+ for (let i = 0; i < diagLen; i++) {
257
+ const val = Array.isArray(value) ? value[i] : value;
258
+ data[kRow + i][kCol + i] = val;
259
+ }
260
+ return new MathJSDenseMatrix({
261
+ data,
262
+ size: [rows, cols]
263
+ });
264
+ }
265
+ };
266
+ Object.defineProperty(MathJSDenseMatrix.prototype, "isDenseMatrix", {
267
+ value: true,
268
+ writable: false,
269
+ enumerable: false
270
+ });
271
+ Object.defineProperty(MathJSDenseMatrix.prototype, "isMatrix", {
272
+ value: true,
273
+ writable: false,
274
+ enumerable: false
275
+ });
276
+ Object.defineProperty(MathJSDenseMatrix.prototype, "type", {
277
+ value: "DenseMatrix",
278
+ writable: true,
279
+ configurable: true,
280
+ enumerable: false
281
+ });
282
+ var MathJSSparseMatrix = class MathJSSparseMatrix {
283
+ _values;
284
+ _index;
285
+ _ptr;
286
+ _size;
287
+ _datatype;
288
+ constructor(data) {
289
+ if (!data) {
290
+ this._values = [];
291
+ this._index = [];
292
+ this._ptr = [0];
293
+ this._size = [0, 0];
294
+ return;
295
+ }
296
+ if (Array.isArray(data)) {
297
+ this._values = [];
298
+ this._index = [];
299
+ this._ptr = [];
300
+ this._size = [];
301
+ this._fromDenseArray(data);
302
+ return;
303
+ }
304
+ if (data.data) {
305
+ this._values = [];
306
+ this._index = [];
307
+ this._ptr = [];
308
+ this._size = [];
309
+ this._fromDenseArray(data.data);
310
+ this._datatype = data.datatype ?? data._datatype;
311
+ return;
312
+ }
313
+ const values = data.values !== void 0 ? data.values : data._values;
314
+ const index = data.index ?? data._index;
315
+ const ptr = data.ptr ?? data._ptr;
316
+ const size = data.size ?? data._size;
317
+ this._values = values != null ? values : null;
318
+ this._index = index ?? [];
319
+ this._ptr = ptr ?? [0];
320
+ this._size = size ?? [0, 0];
321
+ this._datatype = data.datatype ?? data._datatype;
322
+ }
323
+ _fromDenseArray(data) {
324
+ const rows = data.length;
325
+ const cols = rows > 0 && Array.isArray(data[0]) ? data[0].length : 0;
326
+ this._values = [];
327
+ this._index = [];
328
+ this._ptr = [0];
329
+ this._size = [rows, cols];
330
+ for (let j = 0; j < cols; j++) {
331
+ for (let i = 0; i < rows; i++) {
332
+ const v = data[i][j];
333
+ if (v !== 0 && v != null) {
334
+ this._values.push(v);
335
+ this._index.push(i);
336
+ }
337
+ }
338
+ this._ptr.push(this._values.length);
339
+ }
340
+ }
341
+ get rows() {
342
+ return this._size[0] ?? 0;
343
+ }
344
+ get cols() {
345
+ return this._size[1] ?? 0;
346
+ }
347
+ storage() {
348
+ return "sparse";
349
+ }
350
+ datatype() {
351
+ return this._datatype;
352
+ }
353
+ size() {
354
+ return [...this._size];
355
+ }
356
+ get(index) {
357
+ const [i, j] = index;
358
+ if (j < 0 || j >= this._size[1] || i < 0 || i >= this._size[0]) throw new RangeError(`Index out of range (${i}, ${j}) for matrix of size [${this._size}]`);
359
+ for (let k = this._ptr[j]; k < this._ptr[j + 1]; k++) if (this._index[k] === i) return this._values ? this._values[k] : 1;
360
+ return 0;
361
+ }
362
+ set(index, value, _defaultValue) {
363
+ const [i, j] = index;
364
+ if (i >= this._size[0]) this._size[0] = i + 1;
365
+ if (j >= this._size[1]) {
366
+ while (this._ptr.length <= j + 1) this._ptr.push(this._ptr[this._ptr.length - 1]);
367
+ this._size[1] = j + 1;
368
+ }
369
+ const start = this._ptr[j];
370
+ const end = this._ptr[j + 1];
371
+ let pos = start;
372
+ while (pos < end && this._index[pos] < i) pos++;
373
+ if (pos < end && this._index[pos] === i) {
374
+ if (value === 0) {
375
+ this._index.splice(pos, 1);
376
+ if (this._values) this._values.splice(pos, 1);
377
+ for (let c = j + 1; c < this._ptr.length; c++) this._ptr[c]--;
378
+ } else if (this._values) this._values[pos] = value;
379
+ } else if (value !== 0) {
380
+ this._index.splice(pos, 0, i);
381
+ if (this._values) this._values.splice(pos, 0, value);
382
+ for (let c = j + 1; c < this._ptr.length; c++) this._ptr[c]++;
383
+ }
384
+ return this;
385
+ }
386
+ valueOf() {
387
+ const [rows, cols] = this._size;
388
+ const result = Array.from({ length: rows }, () => new Array(cols).fill(0));
389
+ for (let j = 0; j < cols; j++) for (let k = this._ptr[j]; k < this._ptr[j + 1]; k++) result[this._index[k]][j] = this._values ? this._values[k] : 1;
390
+ return result;
391
+ }
392
+ toArray() {
393
+ return this.valueOf();
394
+ }
395
+ clone() {
396
+ const m = new MathJSSparseMatrix({
397
+ values: this._values ? [...this._values] : null,
398
+ index: [...this._index],
399
+ ptr: [...this._ptr],
400
+ size: [...this._size]
401
+ });
402
+ m._datatype = this._datatype;
403
+ return m;
404
+ }
405
+ create(data, datatype) {
406
+ const m = new MathJSSparseMatrix(data);
407
+ m._datatype = datatype;
408
+ return m;
409
+ }
410
+ createSparseMatrix(opts) {
411
+ return new MathJSSparseMatrix(opts);
412
+ }
413
+ map(callback) {
414
+ const [rows, cols] = this._size;
415
+ const newValues = [];
416
+ const newIndex = [];
417
+ const newPtr = [0];
418
+ for (let j = 0; j < cols; j++) {
419
+ for (let k = this._ptr[j]; k < this._ptr[j + 1]; k++) {
420
+ const i = this._index[k];
421
+ const result = callback(this._values ? this._values[k] : 1, [i, j], this);
422
+ if (result !== 0) {
423
+ newValues.push(result);
424
+ newIndex.push(i);
425
+ }
426
+ }
427
+ newPtr.push(newValues.length);
428
+ }
429
+ const m = new MathJSSparseMatrix({
430
+ values: newValues,
431
+ index: newIndex,
432
+ ptr: newPtr,
433
+ size: [rows, cols]
434
+ });
435
+ m._datatype = this._datatype;
436
+ return m;
437
+ }
438
+ forEach(callback) {
439
+ const cols = this._size[1];
440
+ for (let j = 0; j < cols; j++) for (let k = this._ptr[j]; k < this._ptr[j + 1]; k++) {
441
+ const i = this._index[k];
442
+ callback(this._values ? this._values[k] : 1, [i, j], this);
443
+ }
444
+ }
445
+ resize(newSize, _defaultValue) {
446
+ const [newRows, newCols] = newSize;
447
+ const oldCols = this._size[1];
448
+ if (newCols < oldCols) {
449
+ const nnzKeep = this._ptr[newCols];
450
+ this._values = this._values ? this._values.slice(0, nnzKeep) : null;
451
+ this._index = this._index.slice(0, nnzKeep);
452
+ this._ptr = this._ptr.slice(0, newCols + 1);
453
+ } else if (newCols > oldCols) {
454
+ const lastNnz = this._ptr[this._ptr.length - 1];
455
+ while (this._ptr.length <= newCols) this._ptr.push(lastNnz);
456
+ }
457
+ if (newRows < this._size[0]) {
458
+ const vals = [];
459
+ const idx = [];
460
+ const ptr = [0];
461
+ const cols = Math.min(newCols, this._ptr.length - 1);
462
+ for (let j = 0; j < cols; j++) {
463
+ for (let k = this._ptr[j]; k < this._ptr[j + 1]; k++) if (this._index[k] < newRows) {
464
+ if (this._values) vals.push(this._values[k]);
465
+ idx.push(this._index[k]);
466
+ }
467
+ ptr.push(idx.length);
468
+ }
469
+ this._values = this._values ? vals : null;
470
+ this._index = idx;
471
+ this._ptr = ptr;
472
+ }
473
+ this._size = [newRows, newCols];
474
+ return this;
475
+ }
476
+ toJSON() {
477
+ return {
478
+ mathjs: "SparseMatrix",
479
+ values: this._values,
480
+ index: this._index,
481
+ ptr: this._ptr,
482
+ size: this._size
483
+ };
484
+ }
485
+ toString() {
486
+ const lines = [];
487
+ const cols = this._size[1];
488
+ for (let j = 0; j < cols; j++) for (let k = this._ptr[j]; k < this._ptr[j + 1]; k++) {
489
+ const v = this._values ? this._values[k] : 1;
490
+ lines.push(` (${this._index[k]}, ${j}) ==> ${v}`);
491
+ }
492
+ return `Sparse Matrix [${this._size[0]} x ${this._size[1]}] (${this._index.length} non-zero)\n` + lines.join("\n");
493
+ }
494
+ static diagonal(size, value, k = 0, defaultValue = 0, _datatype) {
495
+ const [rows, cols] = size;
496
+ const kRow = k < 0 ? -k : 0;
497
+ const kCol = k > 0 ? k : 0;
498
+ const diagLen = Math.min(rows - kRow, cols - kCol);
499
+ const values = [];
500
+ const index = [];
501
+ const ptr = [0];
502
+ for (let j = 0; j < cols; j++) {
503
+ const diagIdx = j - kCol;
504
+ if (diagIdx >= 0 && diagIdx < diagLen) {
505
+ const v = Array.isArray(value) ? value[diagIdx] : value;
506
+ if (v !== 0 && v !== defaultValue) {
507
+ values.push(v);
508
+ index.push(kRow + diagIdx);
509
+ }
510
+ }
511
+ ptr.push(values.length);
512
+ }
513
+ return new MathJSSparseMatrix({
514
+ values,
515
+ index,
516
+ ptr,
517
+ size: [rows, cols]
518
+ });
519
+ }
520
+ static _swapRows(j, pi, n, values, index, ptr) {
521
+ for (let c = 0; c < n; c++) {
522
+ let jPos = -1;
523
+ let piPos = -1;
524
+ for (let k = ptr[c]; k < ptr[c + 1]; k++) {
525
+ if (index[k] === j) jPos = k;
526
+ if (index[k] === pi) piPos = k;
527
+ }
528
+ if (jPos !== -1 && piPos !== -1) {
529
+ if (values) {
530
+ const tmp = values[jPos];
531
+ values[jPos] = values[piPos];
532
+ values[piPos] = tmp;
533
+ }
534
+ } else if (jPos !== -1) {
535
+ const vj = values ? values[jPos] : void 0;
536
+ index.splice(jPos, 1);
537
+ if (values) values.splice(jPos, 1);
538
+ let insertPos = ptr[c];
539
+ const endPos = ptr[c + 1] - 1;
540
+ while (insertPos <= endPos && index[insertPos] < pi) insertPos++;
541
+ index.splice(insertPos, 0, pi);
542
+ if (values) values.splice(insertPos, 0, vj);
543
+ } else if (piPos !== -1) {
544
+ const vpi = values ? values[piPos] : void 0;
545
+ index.splice(piPos, 1);
546
+ if (values) values.splice(piPos, 1);
547
+ let insertPos = ptr[c];
548
+ const endPos = ptr[c + 1] - 1;
549
+ while (insertPos <= endPos && index[insertPos] < j) insertPos++;
550
+ index.splice(insertPos, 0, j);
551
+ if (values) values.splice(insertPos, 0, vpi);
552
+ }
553
+ }
554
+ }
555
+ static _forEachRow(j, values, index, ptr, callback) {
556
+ const n = ptr.length - 1;
557
+ for (let c = 0; c < n; c++) for (let k = ptr[c]; k < ptr[c + 1]; k++) if (index[k] === j) callback(c, values ? values[k] : 1);
558
+ }
559
+ };
560
+ Object.defineProperty(MathJSSparseMatrix.prototype, "isDenseMatrix", {
561
+ value: false,
562
+ writable: false,
563
+ enumerable: false
564
+ });
565
+ Object.defineProperty(MathJSSparseMatrix.prototype, "isSparseMatrix", {
566
+ value: true,
567
+ writable: false,
568
+ enumerable: false
569
+ });
570
+ Object.defineProperty(MathJSSparseMatrix.prototype, "isMatrix", {
571
+ value: true,
572
+ writable: false,
573
+ enumerable: false
574
+ });
575
+ Object.defineProperty(MathJSSparseMatrix.prototype, "type", {
576
+ value: "SparseMatrix",
577
+ writable: false,
578
+ enumerable: false
579
+ });
580
+ function createMatrixBridge() {
581
+ return function matrix(data, storageType) {
582
+ if (typeof data === "string") return data === "sparse" ? new MathJSSparseMatrix() : new MathJSDenseMatrix();
583
+ if (!data) return storageType === "sparse" ? new MathJSSparseMatrix() : new MathJSDenseMatrix();
584
+ if (data instanceof MathJSSparseMatrix) return data;
585
+ if (data instanceof MathJSDenseMatrix) {
586
+ if (storageType === "sparse") return new MathJSSparseMatrix(data._data);
587
+ return data;
588
+ }
589
+ return storageType === "sparse" ? new MathJSSparseMatrix(data) : new MathJSDenseMatrix(data);
590
+ };
591
+ }
592
+ function inferSize(data) {
593
+ if (data.length === 0) return [0];
594
+ if (Array.isArray(data[0])) return [data.length, data[0].length];
595
+ return [data.length];
596
+ }
597
+ //#endregion
598
+ //#region src/wasm/resolve.ts
599
+ async function resolveBrowserWasm(metaUrl, wasmFile) {
600
+ let dir = new URL(".", metaUrl);
601
+ for (let depth = 0; depth < 8; depth++) {
602
+ const candidates = [new URL(`wasm/${wasmFile}`, dir), new URL(`dist/wasm/${wasmFile}`, dir)];
603
+ for (const candidate of candidates) try {
604
+ if ((await fetch(candidate.href, { method: "HEAD" })).ok) return candidate.href;
605
+ } catch {}
606
+ const parent = new URL("../", dir);
607
+ if (parent.href === dir.href) break;
608
+ dir = parent;
609
+ }
610
+ return new URL(`./wasm/${wasmFile}`, metaUrl).href;
611
+ }
612
+ const wasmLoader = class WasmLoader extends WasmModuleLoader {
613
+ static instance = null;
614
+ constructor() {
615
+ super();
616
+ }
617
+ static getInstance() {
618
+ if (!WasmLoader.instance) WasmLoader.instance = new WasmLoader();
619
+ return WasmLoader.instance;
620
+ }
621
+ async getDefaultWasmPath() {
622
+ const wasmFile = "mathts-as.wasm";
623
+ if (this.isNode) {
624
+ const packaged = await resolvePackagedWasm(import.meta.url, wasmFile);
625
+ if (packaged) return packaged;
626
+ return defaultWasmLocation(import.meta.url, wasmFile);
627
+ }
628
+ return resolveBrowserWasm(import.meta.url, wasmFile);
629
+ }
630
+ getModule() {
631
+ return this.wasmModule;
632
+ }
633
+ getCompiledModule() {
634
+ return this.compiledModule;
635
+ }
636
+ isLoaded() {
637
+ return this.wasmModule !== null;
638
+ }
639
+ isPrecompiled() {
640
+ return this.compiledModule !== null;
641
+ }
642
+ getLoadingMetrics() {
643
+ return this.lastMetrics;
644
+ }
645
+ collect() {
646
+ const module = this.wasmModule;
647
+ if (!module) return;
648
+ module.__collect();
649
+ }
650
+ reset() {
651
+ this.wasmModule = null;
652
+ this.compiledModule = null;
653
+ this.loading = null;
654
+ this.lastMetrics = null;
655
+ }
656
+ }.getInstance();
657
+ const INTEGRITY_FAILURE = "WASM integrity check failed";
658
+ async function loadWasm(wasmPath) {
659
+ try {
660
+ await wasmLoader.load(wasmPath);
661
+ return true;
662
+ } catch (error) {
663
+ if (error instanceof Error && error.message.startsWith(INTEGRITY_FAILURE)) throw error;
664
+ return false;
665
+ }
666
+ }
667
+ function isWasmLoaded() {
668
+ return wasmLoader.isLoaded();
669
+ }
670
+ //#endregion
671
+ //#region src/wasm/policy.ts
672
+ const WASM_DISPATCH_POLICY = {
673
+ array_abs_ptr: { min: 1024 },
674
+ array_log10_ptr: { min: 1024 },
675
+ array_sin_ptr: {
676
+ min: 1024,
677
+ max: 131072
678
+ },
679
+ array_log1p_ptr: {
680
+ min: 1024,
681
+ max: 16384
682
+ },
683
+ array_cos_ptr: { min: 16384 },
684
+ array_atanh_ptr: { min: 16384 },
685
+ array_log_ptr: { min: 16384 },
686
+ array_sec_ptr: {
687
+ min: 16384,
688
+ max: 1048576
689
+ },
690
+ fused_chain: { min: 1024 },
691
+ poly_fit_f64: { min: 1024 },
692
+ cheb_fit_f64: { min: 1024 },
693
+ legendre_fit_f64: { min: 1024 },
694
+ lgamma_f64: { min: 1048576 },
695
+ sort_f64: { min: 1048576 }
696
+ };
697
+ function wasmPolicyAllows(kernel, n) {
698
+ const band = WASM_DISPATCH_POLICY[kernel];
699
+ return band != null && n >= band.min && (band.max === void 0 || n < band.max);
700
+ }
701
+ //#endregion
702
+ //#region src/wasm/bridges/common.ts
703
+ function getWasm() {
704
+ try {
705
+ return wasmLoader.getModule();
706
+ } catch {
707
+ return null;
708
+ }
709
+ }
710
+ function isAsWasm(wasm) {
711
+ return !!wasm && typeof wasm["array_sin_ptr"] === "function";
712
+ }
713
+ let scratchBase = -1;
714
+ function ensureScratch(mem, need) {
715
+ if (scratchBase < 0) scratchBase = mem.buffer.byteLength;
716
+ if (scratchBase + need > mem.buffer.byteLength) mem.grow(Math.ceil((scratchBase + need - mem.buffer.byteLength) / 65536));
717
+ return scratchBase;
718
+ }
719
+ function runUnaryPtr(mem, fn, xs) {
720
+ return runChainPtr(mem, [fn], xs);
721
+ }
722
+ function runChainPtr(mem, fns, xs) {
723
+ const n = xs.length;
724
+ try {
725
+ const base = ensureScratch(mem, 2 * n * 8);
726
+ const bufA = base;
727
+ const bufB = base + n * 8;
728
+ new Float64Array(mem.buffer, bufA, n).set(xs);
729
+ let cur = bufA;
730
+ let other = bufB;
731
+ for (const fn of fns) {
732
+ fn(cur, other, n);
733
+ const t = cur;
734
+ cur = other;
735
+ other = t;
736
+ }
737
+ const result = new Float64Array(n);
738
+ result.set(new Float64Array(mem.buffer, cur, n));
739
+ return result;
740
+ } catch {
741
+ return null;
742
+ }
743
+ }
744
+ const AS_ID_FLOAT64_ARRAY = 5;
745
+ const AS_ID_INT32_ARRAY = 6;
746
+ function resetAsHeap(mod) {
747
+ if (typeof mod.heap_reset === "function") mod.heap_reset();
748
+ }
749
+ function asUnpin(mod, a) {
750
+ mod.__unpin(a.headerPtr);
751
+ mod.__unpin(a.bufferPtr);
752
+ }
753
+ function asReadReturned(mod, headerPtr, Ctor, shift) {
754
+ const dv = new DataView(mod.memory.buffer);
755
+ const dataStart = dv.getUint32((headerPtr >>> 0) + 4, true);
756
+ const len = dv.getUint32((headerPtr >>> 0) + 8, true) >>> shift;
757
+ return new Ctor(new Ctor(mod.memory.buffer, dataStart, len));
758
+ }
759
+ function asReadReturnedF64(mod, headerPtr) {
760
+ return asReadReturned(mod, headerPtr, Float64Array, 3);
761
+ }
762
+ function asReadReturnedI32(mod, headerPtr) {
763
+ return asReadReturned(mod, headerPtr, Int32Array, 2);
764
+ }
765
+ function withAsTyped(wasm, inputs, body, opts) {
766
+ const mod = wasm;
767
+ if (typeof mod.__new !== "function" || typeof mod.__unpin !== "function") return null;
768
+ const allocs = [];
769
+ try {
770
+ const headers = [];
771
+ for (const arr of inputs) {
772
+ const a = allocAsHeader(mod, arr.length * opts.bytes, opts.typeId);
773
+ new opts.Ctor(mod.memory.buffer, a.bufferPtr, arr.length).set(arr);
774
+ allocs.push(a);
775
+ headers.push(a.headerPtr);
776
+ }
777
+ return body(mod, headers);
778
+ } catch {
779
+ return null;
780
+ } finally {
781
+ for (const a of allocs) try {
782
+ asUnpin(mod, a);
783
+ } catch {}
784
+ try {
785
+ resetAsHeap(mod);
786
+ } catch {}
787
+ }
788
+ }
789
+ function withAsF64(wasm, inputs, body) {
790
+ return withAsTyped(wasm, inputs, body, {
791
+ bytes: 8,
792
+ typeId: AS_ID_FLOAT64_ARRAY,
793
+ Ctor: Float64Array
794
+ });
795
+ }
796
+ function withAsI32(wasm, inputs, body) {
797
+ return withAsTyped(wasm, inputs, body, {
798
+ bytes: 4,
799
+ typeId: AS_ID_INT32_ARRAY,
800
+ Ctor: Int32Array
801
+ });
802
+ }
803
+ function makeUnaryArrayDispatch(cfg) {
804
+ return (xs) => {
805
+ if (xs.length >= cfg.threshold && wasmPolicyAllows(cfg.name, xs.length)) {
806
+ const wasm = getWasm();
807
+ if (wasm && isAsWasm(wasm)) {
808
+ const out = withAsF64(wasm, [xs], (mod, [h]) => asReadReturnedF64(mod, mod[cfg.name](h)));
809
+ if (out) return out;
810
+ }
811
+ }
812
+ return cfg.js(xs);
813
+ };
814
+ }
815
+ const kernelName = (op) => `array_${op}_ptr`;
816
+ function elementwiseUnaryDispatch(op, xs) {
817
+ const n = xs.length;
818
+ if (n < 1024 || !wasmPolicyAllows(kernelName(op), n)) return null;
819
+ const wasm = getWasm();
820
+ if (!wasm) return null;
821
+ const fn = wasm[kernelName(op)];
822
+ const mem = wasm.memory;
823
+ if (typeof fn !== "function" || !(mem instanceof WebAssembly.Memory)) return null;
824
+ return runUnaryPtr(mem, fn, xs);
825
+ }
826
+ function elementwiseChainDispatch(ops, xs) {
827
+ const n = xs.length;
828
+ if (ops.length === 0 || n < 1024) return null;
829
+ if (!wasmPolicyAllows("fused_chain", n)) return null;
830
+ const wasm = getWasm();
831
+ if (!wasm) return null;
832
+ const mem = wasm.memory;
833
+ if (!(mem instanceof WebAssembly.Memory)) return null;
834
+ const kernels = [];
835
+ for (const op of ops) {
836
+ const fn = wasm[kernelName(op)];
837
+ if (typeof fn !== "function") return null;
838
+ kernels.push(fn);
839
+ }
840
+ return runChainPtr(mem, kernels, xs);
841
+ }
842
+ //#endregion
843
+ //#region src/typed/arithmetic.ts
844
+ function elementwise(op, a, b) {
845
+ const aArr = Array.isArray(a);
846
+ const bArr = Array.isArray(b);
847
+ if (aArr && bArr) {
848
+ if (a.length !== b.length) throw new RangeError(`Dimension mismatch (${a.length} != ${b.length}) in element-wise operation`);
849
+ return a.map((x, i) => elementwise(op, x, b[i]));
850
+ }
851
+ if (aArr) return a.map((x) => elementwise(op, x, b));
852
+ if (bArr) return b.map((y) => elementwise(op, a, y));
853
+ return op(a, b);
854
+ }
855
+ const numberBinCache = /* @__PURE__ */ new WeakMap();
856
+ function getNumberBin(tf, fallback) {
857
+ let f = numberBinCache.get(tf);
858
+ if (!f) {
859
+ let found = null;
860
+ try {
861
+ found = mathTyped.find(tf, ["number", "number"]);
862
+ } catch {
863
+ found = null;
864
+ }
865
+ f = found ?? ((a, b) => fallback(a, b));
866
+ numberBinCache.set(tf, f);
867
+ }
868
+ return f;
869
+ }
870
+ function arrayAllNumbersFlat(a) {
871
+ for (let i = 0; i < a.length; i++) if (typeof a[i] !== "number") return false;
872
+ return true;
873
+ }
874
+ function arrayAllNumbersPair(a, b) {
875
+ if (a.length !== b.length) return false;
876
+ for (let i = 0; i < a.length; i++) if (typeof a[i] !== "number" || typeof b[i] !== "number") return false;
877
+ return true;
878
+ }
879
+ function elementwiseNumber(tf, fallback, a, b) {
880
+ const f = getNumberBin(tf, fallback);
881
+ const aArr = Array.isArray(a);
882
+ const bArr = Array.isArray(b);
883
+ if (aArr && bArr) {
884
+ if (a.length !== b.length) throw new RangeError(`Dimension mismatch (${a.length} != ${b.length}) in element-wise operation`);
885
+ if (a.constructor !== Array || b.constructor !== Array) return elementwise(fallback, a, b);
886
+ if (a.length > 0 && (Array.isArray(a[0]) || Array.isArray(b[0]))) {
887
+ const out = new Array(a.length);
888
+ for (let i = 0; i < a.length; i++) out[i] = elementwiseNumber(tf, fallback, a[i], b[i]);
889
+ return out;
890
+ }
891
+ if (arrayAllNumbersPair(a, b)) {
892
+ const n = a.length;
893
+ const out = new Array(n);
894
+ for (let i = 0; i < n; i++) out[i] = f(a[i], b[i]);
895
+ return out;
896
+ }
897
+ return elementwise(fallback, a, b);
898
+ }
899
+ if (aArr) {
900
+ if (a.constructor !== Array || typeof b !== "number") return elementwise(fallback, a, b);
901
+ if (a.length > 0 && Array.isArray(a[0])) return a.map((x) => elementwiseNumber(tf, fallback, x, b));
902
+ if (arrayAllNumbersFlat(a)) {
903
+ const out = new Array(a.length);
904
+ for (let i = 0; i < a.length; i++) out[i] = f(a[i], b);
905
+ return out;
906
+ }
907
+ return elementwise(fallback, a, b);
908
+ }
909
+ if (bArr) {
910
+ if (b.constructor !== Array || typeof a !== "number") return elementwise(fallback, a, b);
911
+ if (b.length > 0 && Array.isArray(b[0])) return b.map((y) => elementwiseNumber(tf, fallback, a, y));
912
+ if (arrayAllNumbersFlat(b)) {
913
+ const out = new Array(b.length);
914
+ for (let i = 0; i < b.length; i++) out[i] = f(a, b[i]);
915
+ return out;
916
+ }
917
+ return elementwise(fallback, a, b);
918
+ }
919
+ return fallback(a, b);
920
+ }
921
+ function elementwiseMatrixNumber(tf, fallback, a, b) {
922
+ const data = elementwiseNumber(tf, fallback, toNested(a), toNested(b));
923
+ return isSparseStorage(a) || isSparseStorage(b) ? new MathJSSparseMatrix(data) : new MathJSDenseMatrix(data);
924
+ }
925
+ function isSparseStorage(m) {
926
+ const s = m.storage;
927
+ return typeof s === "function" && s.call(m) === "sparse";
928
+ }
929
+ function toNested(m) {
930
+ const t = m.toArray;
931
+ return typeof t === "function" ? t.call(m) : m;
932
+ }
933
+ const addOp = (x, y) => add(x, y);
934
+ const subOp = (x, y) => subtract(x, y);
935
+ const mulOp = (x, y) => multiply(x, y);
936
+ const addForNumberPath = {};
937
+ const subtractForNumberPath = {};
938
+ const multiplyForNumberPath = {};
939
+ const asUnit = (u) => u;
940
+ function unitSameDimension(a, b) {
941
+ return asUnit(a).equalBase(b);
942
+ }
943
+ function unitCmp(a, b) {
944
+ if (!unitSameDimension(a, b)) throw new Error("Cannot compare units with different dimensions");
945
+ const va = asUnit(a).value;
946
+ const vb = asUnit(b).value;
947
+ return va > vb ? 1 : va < vb ? -1 : 0;
948
+ }
949
+ function unitAddSub(a, b, op) {
950
+ const ua = asUnit(a);
951
+ const ub = asUnit(b);
952
+ if (!ua.equalBase(b)) throw new Error("Cannot add/subtract units with different dimensions");
953
+ if (ua.value == null || ub.value == null) throw new Error("Cannot add/subtract a valueless unit");
954
+ const res = ua.clone();
955
+ res.value = op(ua.value, ub.value);
956
+ return res;
957
+ }
958
+ const unitAdd = (a, b) => unitAddSub(a, b, addOp);
959
+ const unitSub = (a, b) => unitAddSub(a, b, (x, y) => subtract(x, y));
960
+ const unitMul = (a, b) => asUnit(a).multiply(b);
961
+ const unitDiv = (a, b) => asUnit(a).divide(b);
962
+ const add = mathTyped("add", {
963
+ "number, number": (a, b) => a + b,
964
+ "bigint, bigint": (a, b) => a + b,
965
+ "Complex, Complex": (a, b) => a.add(b),
966
+ "Fraction, Fraction": (a, b) => a.add(b),
967
+ "BigNumber, BigNumber": (a, b) => a.add(b),
968
+ "Unit, Unit": (a, b) => unitAdd(a, b),
969
+ "Dual, Dual": (a, b) => a.add(b),
970
+ "Dual, number": (a, b) => a.add(Dual.constant(b)),
971
+ "number, Dual": (a, b) => Dual.constant(a).add(b),
972
+ "number, Complex": (a, b) => Complex.fromNumber(a).add(b),
973
+ "Complex, number": (a, b) => a.add(Complex.fromNumber(b)),
974
+ "number, Fraction": (a, b) => Fraction.fromNumber(a).add(b),
975
+ "Fraction, number": (a, b) => a.add(Fraction.fromNumber(b)),
976
+ "number, BigNumber": (a, b) => BigNumber.fromNumber(a).add(b),
977
+ "BigNumber, number": (a, b) => a.add(BigNumber.fromNumber(b)),
978
+ "Float64Array, Float64Array": async (a, b) => {
979
+ return (await computePool.add(a, b)).result;
980
+ },
981
+ "Array, Array": (a, b) => elementwiseNumber(addForNumberPath.fn, addOp, a, b),
982
+ "Array, number": (a, b) => elementwiseNumber(addForNumberPath.fn, addOp, a, b),
983
+ "number, Array": (a, b) => elementwiseNumber(addForNumberPath.fn, addOp, a, b),
984
+ "DenseMatrix, DenseMatrix": (a, b) => elementwiseMatrixNumber(addForNumberPath.fn, addOp, a, b),
985
+ "SparseMatrix, SparseMatrix": (a, b) => elementwiseMatrixNumber(addForNumberPath.fn, addOp, a, b),
986
+ "DenseMatrix, number": (a, b) => elementwiseMatrixNumber(addForNumberPath.fn, addOp, a, b),
987
+ "number, DenseMatrix": (a, b) => elementwiseMatrixNumber(addForNumberPath.fn, addOp, a, b),
988
+ "SparseMatrix, number": (a, b) => elementwiseMatrixNumber(addForNumberPath.fn, addOp, a, b),
989
+ "number, SparseMatrix": (a, b) => elementwiseMatrixNumber(addForNumberPath.fn, addOp, a, b),
990
+ "any, any, ...any": (a, b, rest) => {
991
+ const op = add;
992
+ let result = op(a, b);
993
+ for (let i = 0; i < rest.length; i++) result = op(result, rest[i]);
994
+ return result;
995
+ }
996
+ });
997
+ addForNumberPath.fn = add;
998
+ const subtract = mathTyped("subtract", {
999
+ "number, number": (a, b) => a - b,
1000
+ "bigint, bigint": (a, b) => a - b,
1001
+ "Complex, Complex": (a, b) => a.subtract(b),
1002
+ "Fraction, Fraction": (a, b) => a.subtract(b),
1003
+ "BigNumber, BigNumber": (a, b) => a.subtract(b),
1004
+ "Unit, Unit": (a, b) => unitSub(a, b),
1005
+ "Dual, Dual": (a, b) => a.sub(b),
1006
+ "Dual, number": (a, b) => a.sub(Dual.constant(b)),
1007
+ "number, Dual": (a, b) => Dual.constant(a).sub(b),
1008
+ "number, Complex": (a, b) => Complex.fromNumber(a).subtract(b),
1009
+ "Complex, number": (a, b) => a.subtract(Complex.fromNumber(b)),
1010
+ "number, Fraction": (a, b) => Fraction.fromNumber(a).subtract(b),
1011
+ "Fraction, number": (a, b) => a.subtract(Fraction.fromNumber(b)),
1012
+ "number, BigNumber": (a, b) => BigNumber.fromNumber(a).subtract(b),
1013
+ "BigNumber, number": (a, b) => a.subtract(BigNumber.fromNumber(b)),
1014
+ "Float64Array, Float64Array": async (a, b) => {
1015
+ return (await computePool.subtract(a, b)).result;
1016
+ },
1017
+ "Array, Array": (a, b) => elementwiseNumber(subtractForNumberPath.fn, subOp, a, b),
1018
+ "Array, number": (a, b) => elementwiseNumber(subtractForNumberPath.fn, subOp, a, b),
1019
+ "number, Array": (a, b) => elementwiseNumber(subtractForNumberPath.fn, subOp, a, b),
1020
+ "DenseMatrix, DenseMatrix": (a, b) => elementwiseMatrixNumber(subtractForNumberPath.fn, subOp, a, b),
1021
+ "SparseMatrix, SparseMatrix": (a, b) => elementwiseMatrixNumber(subtractForNumberPath.fn, subOp, a, b),
1022
+ "DenseMatrix, number": (a, b) => elementwiseMatrixNumber(subtractForNumberPath.fn, subOp, a, b),
1023
+ "number, DenseMatrix": (a, b) => elementwiseMatrixNumber(subtractForNumberPath.fn, subOp, a, b),
1024
+ "SparseMatrix, number": (a, b) => elementwiseMatrixNumber(subtractForNumberPath.fn, subOp, a, b),
1025
+ "number, SparseMatrix": (a, b) => elementwiseMatrixNumber(subtractForNumberPath.fn, subOp, a, b)
1026
+ });
1027
+ subtractForNumberPath.fn = subtract;
1028
+ const multiply = mathTyped("multiply", {
1029
+ "number, number": (a, b) => a * b,
1030
+ "bigint, bigint": (a, b) => a * b,
1031
+ "Complex, Complex": (a, b) => a.multiply(b),
1032
+ "Fraction, Fraction": (a, b) => a.multiply(b),
1033
+ "BigNumber, BigNumber": (a, b) => a.multiply(b),
1034
+ "Unit, Unit": (a, b) => unitMul(a, b),
1035
+ "Unit, number": (a, b) => unitMul(a, b),
1036
+ "number, Unit": (a, b) => unitMul(b, a),
1037
+ "Dual, Dual": (a, b) => a.mul(b),
1038
+ "Dual, number": (a, b) => a.mul(Dual.constant(b)),
1039
+ "number, Dual": (a, b) => Dual.constant(a).mul(b),
1040
+ "Array, Array": (a, b) => {
1041
+ if (!Array.isArray(a[0]) || !Array.isArray(b[0])) throw new TypeError("multiply(Array, Array) requires two 2-D matrices; use dot() for vector dot products");
1042
+ const A = DenseMatrix.fromArray(a);
1043
+ const B = DenseMatrix.fromArray(b);
1044
+ return backendManager.multiply(A, B).toArray();
1045
+ },
1046
+ "DenseMatrix, DenseMatrix": (a, b) => {
1047
+ const A = DenseMatrix.fromArray(a.toArray());
1048
+ const B = DenseMatrix.fromArray(b.toArray());
1049
+ return new MathJSDenseMatrix(backendManager.multiply(A, B).toArray());
1050
+ },
1051
+ "number, Complex": (a, b) => b.multiply(Complex.fromNumber(a)),
1052
+ "Complex, number": (a, b) => a.multiply(Complex.fromNumber(b)),
1053
+ "number, Fraction": (a, b) => b.multiply(Fraction.fromNumber(a)),
1054
+ "Fraction, number": (a, b) => a.multiply(Fraction.fromNumber(b)),
1055
+ "number, BigNumber": (a, b) => b.multiply(BigNumber.fromNumber(a)),
1056
+ "BigNumber, number": (a, b) => a.multiply(BigNumber.fromNumber(b)),
1057
+ "Float64Array, Float64Array": async (a, b) => {
1058
+ return (await computePool.multiply(a, b)).result;
1059
+ },
1060
+ "Float64Array, number": async (a, scalar) => {
1061
+ return (await computePool.scale(a, scalar)).result;
1062
+ },
1063
+ "number, Float64Array": async (scalar, a) => {
1064
+ return (await computePool.scale(a, scalar)).result;
1065
+ },
1066
+ "Array, number": (a, b) => elementwiseNumber(multiplyForNumberPath.fn, mulOp, a, b),
1067
+ "number, Array": (a, b) => elementwiseNumber(multiplyForNumberPath.fn, mulOp, a, b),
1068
+ "DenseMatrix, number": (a, b) => elementwiseMatrixNumber(multiplyForNumberPath.fn, mulOp, a, b),
1069
+ "number, DenseMatrix": (a, b) => elementwiseMatrixNumber(multiplyForNumberPath.fn, mulOp, a, b),
1070
+ "SparseMatrix, number": (a, b) => elementwiseMatrixNumber(multiplyForNumberPath.fn, mulOp, a, b),
1071
+ "number, SparseMatrix": (a, b) => elementwiseMatrixNumber(multiplyForNumberPath.fn, mulOp, a, b),
1072
+ "any, any, ...any": (a, b, rest) => {
1073
+ const op = multiply;
1074
+ let result = op(a, b);
1075
+ for (let i = 0; i < rest.length; i++) result = op(result, rest[i]);
1076
+ return result;
1077
+ }
1078
+ });
1079
+ multiplyForNumberPath.fn = multiply;
1080
+ const divide = mathTyped("divide", {
1081
+ "number, number": (a, b) => a / b,
1082
+ "bigint, bigint": (a, b) => a / b,
1083
+ "Complex, Complex": (a, b) => a.divide(b),
1084
+ "Fraction, Fraction": (a, b) => a.divide(b),
1085
+ "BigNumber, BigNumber": (a, b) => a.divide(b),
1086
+ "Unit, Unit": (a, b) => unitDiv(a, b),
1087
+ "Unit, number": (a, b) => unitDiv(a, b),
1088
+ "Dual, Dual": (a, b) => a.div(b),
1089
+ "Dual, number": (a, b) => a.div(Dual.constant(b)),
1090
+ "number, Dual": (a, b) => Dual.constant(a).div(b),
1091
+ "number, Complex": (a, b) => Complex.fromNumber(a).divide(b),
1092
+ "Complex, number": (a, b) => a.divide(Complex.fromNumber(b)),
1093
+ "number, Fraction": (a, b) => Fraction.fromNumber(a).divide(b),
1094
+ "Fraction, number": (a, b) => a.divide(Fraction.fromNumber(b)),
1095
+ "number, BigNumber": (a, b) => BigNumber.fromNumber(a).divide(b),
1096
+ "BigNumber, number": (a, b) => a.divide(BigNumber.fromNumber(b)),
1097
+ "Float64Array, Float64Array": async (a, b) => {
1098
+ return (await computePool.divide(a, b)).result;
1099
+ }
1100
+ });
1101
+ const unaryMinus = mathTyped("unaryMinus", {
1102
+ number: (a) => -a,
1103
+ bigint: (a) => -a,
1104
+ Complex: (a) => a.negate(),
1105
+ Fraction: (a) => a.negate(),
1106
+ BigNumber: (a) => a.negate(),
1107
+ Float64Array: async (a) => {
1108
+ return (await computePool.negate(a)).result;
1109
+ }
1110
+ });
1111
+ const unaryPlus = mathTyped("unaryPlus", {
1112
+ number: (a) => +a,
1113
+ bigint: (a) => a,
1114
+ Complex: (a) => a,
1115
+ Fraction: (a) => a,
1116
+ BigNumber: (a) => a,
1117
+ Float64Array: (a) => a
1118
+ });
1119
+ const abs = mathTyped("abs", {
1120
+ number: (a) => Math.abs(a),
1121
+ bigint: (a) => a < 0n ? -a : a,
1122
+ Complex: (a) => a.abs(),
1123
+ Fraction: (a) => a.abs(),
1124
+ BigNumber: (a) => a.abs(),
1125
+ Dual: (a) => a.abs(),
1126
+ Unit: (a) => asUnit(a).abs(),
1127
+ Float64Array: async (a) => {
1128
+ const wasm = elementwiseUnaryDispatch("abs", a);
1129
+ if (wasm) return wasm;
1130
+ return (await computePool.abs(a)).result;
1131
+ }
1132
+ });
1133
+ const sign = mathTyped("sign", {
1134
+ number: (a) => Math.sign(a),
1135
+ bigint: (a) => a > 0n ? 1n : a < 0n ? -1n : 0n,
1136
+ Fraction: (a) => new Fraction(BigInt(a.sign()), 1n),
1137
+ BigNumber: (a) => BigNumber.fromNumber(a.sign()),
1138
+ Complex: (a) => {
1139
+ const m = Math.hypot(a.re, a.im);
1140
+ return m === 0 ? new Complex(0, 0) : new Complex(a.re / m, a.im / m);
1141
+ },
1142
+ Float64Array: async (a) => {
1143
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.sign(x)")).result;
1144
+ const out = new Float64Array(a.length);
1145
+ for (let i = 0; i < a.length; i++) out[i] = Math.sign(a[i]);
1146
+ return out;
1147
+ }
1148
+ });
1149
+ const pow$1 = mathTyped("pow", {
1150
+ "number, number": (a, b) => Math.pow(a, b),
1151
+ "bigint, bigint": (a, b) => a ** b,
1152
+ "Complex, number": (a, b) => pow(a, b),
1153
+ "Complex, Complex": (a, b) => pow(a, b),
1154
+ "Fraction, number": (a, b) => pow(a, b),
1155
+ "BigNumber, number": (a, b) => pow(a, b),
1156
+ "BigNumber, BigNumber": (a, b) => pow(a, b),
1157
+ "Dual, number": (a, b) => a.powConst(b),
1158
+ "Dual, Dual": (a, b) => a.pow(b),
1159
+ "Unit, number": (a, b) => a.pow(b),
1160
+ "Array, number": (a, b) => {
1161
+ if (!Array.isArray(a[0])) throw new TypeError("pow(Array, number): expected a square 2-D matrix; use dotPow for element-wise power");
1162
+ const m = a;
1163
+ const n = m.length;
1164
+ if (m.some((row) => row.length !== n)) throw new RangeError(`pow: matrix must be square (got ${n}×${m[0]?.length ?? 0})`);
1165
+ if (!Number.isInteger(b) || b < 0) throw new Error("pow: only non-negative integer exponents are supported for matrices here; use matrixPower(A, p) for negative or fractional powers");
1166
+ let result = DenseMatrix.identity(n);
1167
+ let base = DenseMatrix.fromArray(m);
1168
+ let e = b;
1169
+ while (e > 0) {
1170
+ if (e % 2 === 1) result = backendManager.multiply(result, base);
1171
+ e = Math.floor(e / 2);
1172
+ if (e > 0) base = backendManager.multiply(base, base);
1173
+ }
1174
+ return result.toArray();
1175
+ }
1176
+ });
1177
+ const sqrt = mathTyped("sqrt", {
1178
+ number: (a) => {
1179
+ if (a < 0) return new Complex(0, Math.sqrt(-a));
1180
+ return Math.sqrt(a);
1181
+ },
1182
+ Complex: (a) => a.sqrt(),
1183
+ BigNumber: (a) => a.sqrt(),
1184
+ Dual: (a) => a.sqrt(),
1185
+ Float64Array: async (a) => {
1186
+ return (await computePool.sqrt(a)).result;
1187
+ }
1188
+ });
1189
+ const square = mathTyped("square", {
1190
+ number: (a) => a * a,
1191
+ bigint: (a) => a * a,
1192
+ Complex: (a) => a.multiply(a),
1193
+ Fraction: (a) => a.multiply(a),
1194
+ BigNumber: (a) => a.multiply(a),
1195
+ Dual: (a) => a.square(),
1196
+ Float64Array: async (a) => {
1197
+ return (await computePool.square(a)).result;
1198
+ }
1199
+ });
1200
+ const cube = mathTyped("cube", {
1201
+ number: (a) => a * a * a,
1202
+ bigint: (a) => a * a * a,
1203
+ Complex: (a) => a.multiply(a).multiply(a),
1204
+ Fraction: (a) => a.multiply(a).multiply(a),
1205
+ BigNumber: (a) => a.multiply(a).multiply(a),
1206
+ Dual: (a) => a.powConst(3),
1207
+ Float64Array: async (a) => {
1208
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => x * x * x")).result;
1209
+ const out = new Float64Array(a.length);
1210
+ for (let i = 0; i < a.length; i++) out[i] = a[i] * a[i] * a[i];
1211
+ return out;
1212
+ }
1213
+ });
1214
+ function cbrtAllRoots(z) {
1215
+ const arg3 = z.arg() / 3;
1216
+ const r = Math.cbrt(z.abs());
1217
+ const rotate = (theta) => new Complex(r, 0).mul(new Complex(0, theta).exp());
1218
+ return [
1219
+ rotate(arg3),
1220
+ rotate(arg3 + Math.PI * 2 / 3),
1221
+ rotate(arg3 - Math.PI * 2 / 3)
1222
+ ];
1223
+ }
1224
+ const cbrt = mathTyped("cbrt", {
1225
+ number: (a) => Math.cbrt(a),
1226
+ Complex: (a) => a.pow(1 / 3),
1227
+ BigNumber: (a) => a.cbrt(),
1228
+ Dual: (a) => a.powConst(1 / 3),
1229
+ "number, boolean": (a, allRoots) => {
1230
+ const z = new Complex(a, 0);
1231
+ return allRoots ? cbrtAllRoots(z) : cbrtAllRoots(z)[0];
1232
+ },
1233
+ "Complex, boolean": (a, allRoots) => {
1234
+ return allRoots ? cbrtAllRoots(a) : cbrtAllRoots(a)[0];
1235
+ },
1236
+ Float64Array: async (a) => {
1237
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.cbrt(x)")).result;
1238
+ const out = new Float64Array(a.length);
1239
+ for (let i = 0; i < a.length; i++) out[i] = Math.cbrt(a[i]);
1240
+ return out;
1241
+ }
1242
+ });
1243
+ const nthRoot = mathTyped("nthRoot", {
1244
+ "number, number": (a, n) => Math.pow(a, 1 / n),
1245
+ "Complex, number": (a, n) => a.pow(1 / n),
1246
+ "BigNumber, number": (a, n) => a.pow(1 / n)
1247
+ });
1248
+ const exp = mathTyped("exp", {
1249
+ number: (a) => Math.exp(a),
1250
+ Complex: (a) => a.exp(),
1251
+ BigNumber: (a) => a.exp(),
1252
+ Dual: (a) => a.exp(),
1253
+ Float64Array: async (a) => {
1254
+ const wasm = elementwiseUnaryDispatch("exp", a);
1255
+ if (wasm) return wasm;
1256
+ return (await computePool.exp(a)).result;
1257
+ }
1258
+ });
1259
+ const log = mathTyped("log", {
1260
+ number: (a) => Math.log(a),
1261
+ Complex: (a) => a.log(),
1262
+ BigNumber: (a) => a.ln(),
1263
+ Dual: (a) => a.log(),
1264
+ "number, number": (a, base) => Math.log(a) / Math.log(base),
1265
+ Float64Array: async (a) => {
1266
+ const wasm = elementwiseUnaryDispatch("log", a);
1267
+ if (wasm) return wasm;
1268
+ return (await computePool.log(a)).result;
1269
+ }
1270
+ });
1271
+ const log10 = mathTyped("log10", {
1272
+ number: (a) => Math.log10(a),
1273
+ Complex: (a) => a.log().divide(Complex.fromNumber(Math.LN10)),
1274
+ BigNumber: (a) => a.log10(),
1275
+ Float64Array: async (a) => {
1276
+ const wasm = elementwiseUnaryDispatch("log10", a);
1277
+ if (wasm) return wasm;
1278
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.log10(x)")).result;
1279
+ const out = new Float64Array(a.length);
1280
+ for (let i = 0; i < a.length; i++) out[i] = Math.log10(a[i]);
1281
+ return out;
1282
+ }
1283
+ });
1284
+ const log2 = mathTyped("log2", {
1285
+ number: (a) => Math.log2(a),
1286
+ Complex: (a) => a.log().divide(Complex.fromNumber(Math.LN2)),
1287
+ BigNumber: (a) => a.log2(),
1288
+ Float64Array: async (a) => {
1289
+ const wasm = elementwiseUnaryDispatch("log2", a);
1290
+ if (wasm) return wasm;
1291
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.log2(x)")).result;
1292
+ const out = new Float64Array(a.length);
1293
+ for (let i = 0; i < a.length; i++) out[i] = Math.log2(a[i]);
1294
+ return out;
1295
+ }
1296
+ });
1297
+ const log1p = mathTyped("log1p", {
1298
+ number: (a) => Math.log1p(a),
1299
+ Float64Array: async (a) => {
1300
+ const wasm = elementwiseUnaryDispatch("log1p", a);
1301
+ if (wasm) return wasm;
1302
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.log1p(x)")).result;
1303
+ const out = new Float64Array(a.length);
1304
+ for (let i = 0; i < a.length; i++) out[i] = Math.log1p(a[i]);
1305
+ return out;
1306
+ }
1307
+ });
1308
+ const expm1 = mathTyped("expm1", {
1309
+ number: (a) => Math.expm1(a),
1310
+ Float64Array: async (a) => {
1311
+ const wasm = elementwiseUnaryDispatch("expm1", a);
1312
+ if (wasm) return wasm;
1313
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.expm1(x)")).result;
1314
+ const out = new Float64Array(a.length);
1315
+ for (let i = 0; i < a.length; i++) out[i] = Math.expm1(a[i]);
1316
+ return out;
1317
+ }
1318
+ });
1319
+ const round$1 = mathTyped("round", {
1320
+ number: (a) => Math.round(a),
1321
+ Fraction: (a) => round(a),
1322
+ BigNumber: (a) => round(a),
1323
+ Complex: (a) => round(a),
1324
+ "number, number": (a, decimals) => {
1325
+ const factor = Math.pow(10, decimals);
1326
+ return Math.round(a * factor) / factor;
1327
+ },
1328
+ Float64Array: async (a) => {
1329
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.round(x)")).result;
1330
+ const out = new Float64Array(a.length);
1331
+ for (let i = 0; i < a.length; i++) out[i] = Math.round(a[i]);
1332
+ return out;
1333
+ }
1334
+ });
1335
+ const floor = mathTyped("floor", {
1336
+ number: (a) => Math.floor(a),
1337
+ Fraction: (a) => a.floor(),
1338
+ BigNumber: (a) => a.floor(),
1339
+ Complex: (a) => new Complex(Math.floor(a.re), Math.floor(a.im)),
1340
+ Float64Array: async (a) => {
1341
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.floor(x)")).result;
1342
+ const out = new Float64Array(a.length);
1343
+ for (let i = 0; i < a.length; i++) out[i] = Math.floor(a[i]);
1344
+ return out;
1345
+ }
1346
+ });
1347
+ const ceil = mathTyped("ceil", {
1348
+ number: (a) => Math.ceil(a),
1349
+ Fraction: (a) => a.ceil(),
1350
+ BigNumber: (a) => a.ceil(),
1351
+ Complex: (a) => new Complex(Math.ceil(a.re), Math.ceil(a.im)),
1352
+ Float64Array: async (a) => {
1353
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.ceil(x)")).result;
1354
+ const out = new Float64Array(a.length);
1355
+ for (let i = 0; i < a.length; i++) out[i] = Math.ceil(a[i]);
1356
+ return out;
1357
+ }
1358
+ });
1359
+ const fix$1 = mathTyped("fix", {
1360
+ number: (a) => Math.trunc(a),
1361
+ Fraction: (a) => fix(a),
1362
+ BigNumber: (a) => fix(a),
1363
+ Complex: (a) => fix(a),
1364
+ Float64Array: async (a) => {
1365
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.trunc(x)")).result;
1366
+ const out = new Float64Array(a.length);
1367
+ for (let i = 0; i < a.length; i++) out[i] = Math.trunc(a[i]);
1368
+ return out;
1369
+ }
1370
+ });
1371
+ const mod = mathTyped("mod", {
1372
+ "number, number": (a, b) => (a % b + b) % b,
1373
+ "bigint, bigint": (a, b) => (a % b + b) % b,
1374
+ "Fraction, Fraction": (a, b) => a.mod(b),
1375
+ "BigNumber, BigNumber": (a, b) => a.mod(b)
1376
+ });
1377
+ const gcd = mathTyped("gcd", {
1378
+ "number, number": (a, b) => euclidSnap(a, b, Math.floor),
1379
+ "bigint, bigint": (a, b) => {
1380
+ a = a < 0n ? -a : a;
1381
+ b = b < 0n ? -b : b;
1382
+ while (b !== 0n) {
1383
+ const t = b;
1384
+ b = a % b;
1385
+ a = t;
1386
+ }
1387
+ return a;
1388
+ },
1389
+ "BigNumber, BigNumber": (a, b) => {
1390
+ let x = a.abs();
1391
+ let y = b.abs();
1392
+ while (!y.isZero()) {
1393
+ const t = y;
1394
+ y = x.mod(y);
1395
+ x = t;
1396
+ }
1397
+ return x;
1398
+ }
1399
+ });
1400
+ const lcm = mathTyped("lcm", {
1401
+ "number, number": (a, b) => {
1402
+ const g = gcd(a, b);
1403
+ return Math.abs(a * b) / g;
1404
+ },
1405
+ "bigint, bigint": (a, b) => {
1406
+ const g = gcd(a, b);
1407
+ return (a < 0n ? -a : a) * (b < 0n ? -b : b) / g;
1408
+ },
1409
+ "BigNumber, BigNumber": (a, b) => {
1410
+ const g = gcd(a, b);
1411
+ if (g.isZero()) return BigNumber.fromNumber(0);
1412
+ return a.abs().multiply(b.abs()).divide(g);
1413
+ }
1414
+ });
1415
+ const xgcd = mathTyped("xgcd", {
1416
+ "number, number": (a, b) => {
1417
+ a = Math.floor(a);
1418
+ b = Math.floor(b);
1419
+ let x = 0, lastX = 1;
1420
+ let y = 1, lastY = 0;
1421
+ while (b !== 0) {
1422
+ const q = Math.floor(a / b);
1423
+ [a, b] = [b, a % b];
1424
+ [x, lastX] = [lastX - q * x, x];
1425
+ [y, lastY] = [lastY - q * y, y];
1426
+ }
1427
+ return a < 0 ? [
1428
+ -a,
1429
+ -lastX,
1430
+ -lastY
1431
+ ] : [
1432
+ a,
1433
+ lastX,
1434
+ lastY
1435
+ ];
1436
+ },
1437
+ "bigint, bigint": (a, b) => {
1438
+ let x = 0n, lastX = 1n;
1439
+ let y = 1n, lastY = 0n;
1440
+ while (b !== 0n) {
1441
+ const q = a / b;
1442
+ [a, b] = [b, a % b];
1443
+ [x, lastX] = [lastX - q * x, x];
1444
+ [y, lastY] = [lastY - q * y, y];
1445
+ }
1446
+ return a < 0n ? [
1447
+ -a,
1448
+ -lastX,
1449
+ -lastY
1450
+ ] : [
1451
+ a,
1452
+ lastX,
1453
+ lastY
1454
+ ];
1455
+ },
1456
+ "Fraction, Fraction": (a, b) => {
1457
+ if (!a.isInteger() || !b.isInteger()) throw new Error("Parameters in function xgcd must be integer numbers");
1458
+ const zero = new Fraction(0n, 1n);
1459
+ const one = new Fraction(1n, 1n);
1460
+ let x = zero, lastX = one;
1461
+ let y = one, lastY = zero;
1462
+ while (!b.isZero()) {
1463
+ const q = a.divide(b).floor();
1464
+ const r = a.mod(b);
1465
+ const nextX = lastX.subtract(q.multiply(x));
1466
+ const nextY = lastY.subtract(q.multiply(y));
1467
+ lastX = x;
1468
+ x = nextX;
1469
+ lastY = y;
1470
+ y = nextY;
1471
+ a = b;
1472
+ b = r;
1473
+ }
1474
+ return a.lessThan(zero) ? [
1475
+ a.negate(),
1476
+ lastX.negate(),
1477
+ lastY.negate()
1478
+ ] : [
1479
+ a,
1480
+ !a.isZero() ? lastX : zero,
1481
+ lastY
1482
+ ];
1483
+ }
1484
+ });
1485
+ function is2DArray(arr) {
1486
+ return Array.isArray(arr[0]);
1487
+ }
1488
+ function vectorNorm(arr, p = 2) {
1489
+ if (p === Infinity) return Math.max(...arr.map((x) => Math.abs(x)));
1490
+ if (p === -Infinity) return Math.min(...arr.map((x) => Math.abs(x)));
1491
+ if (p === 0) return arr.filter((x) => x !== 0).length;
1492
+ if (p === 2) return norm2(arr);
1493
+ const terms = new Array(arr.length);
1494
+ for (let i = 0; i < arr.length; i++) terms[i] = Math.pow(Math.abs(arr[i]), p);
1495
+ return Math.pow(pairwiseSum(terms), 1 / p);
1496
+ }
1497
+ function matrixNorm(data, p = "fro") {
1498
+ const rows = data.length;
1499
+ const cols = rows > 0 ? data[0].length : 0;
1500
+ if (p === "fro" || p === "frobenius") {
1501
+ let s = 0;
1502
+ for (let i = 0; i < rows; i++) for (let j = 0; j < cols; j++) s += data[i][j] * data[i][j];
1503
+ return Math.sqrt(s);
1504
+ }
1505
+ if (p === 1) {
1506
+ let max = 0;
1507
+ for (let j = 0; j < cols; j++) {
1508
+ let s = 0;
1509
+ for (let i = 0; i < rows; i++) s += Math.abs(data[i][j]);
1510
+ if (s > max) max = s;
1511
+ }
1512
+ return max;
1513
+ }
1514
+ if (p === Infinity) {
1515
+ let max = 0;
1516
+ for (let i = 0; i < rows; i++) {
1517
+ let s = 0;
1518
+ for (let j = 0; j < cols; j++) s += Math.abs(data[i][j]);
1519
+ if (s > max) max = s;
1520
+ }
1521
+ return max;
1522
+ }
1523
+ if (p === 2) {
1524
+ const sv = singularValues(data);
1525
+ return sv.length > 0 ? Math.max(...sv) : 0;
1526
+ }
1527
+ throw new Error(`Unsupported matrix norm p=${String(p)} (use 'fro', 1, 2, or Infinity)`);
1528
+ }
1529
+ const matrixLike = (m) => m.toArray();
1530
+ const norm = mathTyped("norm", {
1531
+ number: (a) => Math.abs(a),
1532
+ Complex: (a) => a.abs(),
1533
+ BigNumber: (a) => a.abs(),
1534
+ Array: (arr) => is2DArray(arr) ? matrixNorm(arr) : vectorNorm(arr),
1535
+ "Array, number": (arr, p) => is2DArray(arr) ? matrixNorm(arr, p) : vectorNorm(arr, p),
1536
+ "Array, string": (arr, p) => matrixNorm(arr, p),
1537
+ DenseMatrix: (m) => matrixNorm(matrixLike(m)),
1538
+ "DenseMatrix, number": (m, p) => matrixNorm(matrixLike(m), p),
1539
+ "DenseMatrix, string": (m, p) => matrixNorm(matrixLike(m), p),
1540
+ SparseMatrix: (m) => matrixNorm(matrixLike(m)),
1541
+ "SparseMatrix, number": (m, p) => matrixNorm(matrixLike(m), p),
1542
+ "SparseMatrix, string": (m, p) => matrixNorm(matrixLike(m), p),
1543
+ Float64Array: async (a) => {
1544
+ if (computePool.shouldParallelize(a.length, "norm")) return (await computePool.norm(a)).result;
1545
+ return norm2(a);
1546
+ }
1547
+ });
1548
+ const sinh = mathTyped("sinh", {
1549
+ number: (a) => Math.sinh(a),
1550
+ Complex: (a) => a.sinh(),
1551
+ BigNumber: (a) => a.sinh(),
1552
+ Float64Array: async (a) => {
1553
+ const wasm = elementwiseUnaryDispatch("sinh", a);
1554
+ if (wasm) return wasm;
1555
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.sinh(x)")).result;
1556
+ const out = new Float64Array(a.length);
1557
+ for (let i = 0; i < a.length; i++) out[i] = Math.sinh(a[i]);
1558
+ return out;
1559
+ }
1560
+ });
1561
+ const cosh = mathTyped("cosh", {
1562
+ number: (a) => Math.cosh(a),
1563
+ Complex: (a) => a.cosh(),
1564
+ BigNumber: (a) => a.cosh(),
1565
+ Float64Array: async (a) => {
1566
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.cosh(x)")).result;
1567
+ const out = new Float64Array(a.length);
1568
+ for (let i = 0; i < a.length; i++) out[i] = Math.cosh(a[i]);
1569
+ return out;
1570
+ }
1571
+ });
1572
+ const tanh = mathTyped("tanh", {
1573
+ number: (a) => Math.tanh(a),
1574
+ Complex: (a) => a.tanh(),
1575
+ BigNumber: (a) => a.tanh(),
1576
+ Float64Array: async (a) => {
1577
+ const wasm = elementwiseUnaryDispatch("tanh", a);
1578
+ if (wasm) return wasm;
1579
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.tanh(x)")).result;
1580
+ const out = new Float64Array(a.length);
1581
+ for (let i = 0; i < a.length; i++) out[i] = Math.tanh(a[i]);
1582
+ return out;
1583
+ }
1584
+ });
1585
+ const equal$1 = mathTyped("equal", {
1586
+ "number, number": (a, b) => equal(a, b),
1587
+ "bigint, bigint": (a, b) => a === b,
1588
+ "Complex, Complex": (a, b) => equal(a, b),
1589
+ "Fraction, Fraction": (a, b) => equal(a, b),
1590
+ "BigNumber, BigNumber": (a, b) => equal(a, b),
1591
+ "Unit, Unit": (a, b) => unitSameDimension(a, b) && asUnit(a).value === asUnit(b).value
1592
+ });
1593
+ const smaller = mathTyped("smaller", {
1594
+ "number, number": (a, b) => a < b,
1595
+ "bigint, bigint": (a, b) => a < b,
1596
+ "Fraction, Fraction": (a, b) => a.compare(b) < 0,
1597
+ "BigNumber, BigNumber": (a, b) => a.compare(b) < 0,
1598
+ "Unit, Unit": (a, b) => unitCmp(a, b) < 0
1599
+ });
1600
+ const larger = mathTyped("larger", {
1601
+ "number, number": (a, b) => a > b,
1602
+ "bigint, bigint": (a, b) => a > b,
1603
+ "Fraction, Fraction": (a, b) => a.compare(b) > 0,
1604
+ "BigNumber, BigNumber": (a, b) => a.compare(b) > 0,
1605
+ "Unit, Unit": (a, b) => unitCmp(a, b) > 0
1606
+ });
1607
+ const smallerEq = mathTyped("smallerEq", {
1608
+ "number, number": (a, b) => a <= b,
1609
+ "bigint, bigint": (a, b) => a <= b,
1610
+ "Fraction, Fraction": (a, b) => a.compare(b) <= 0,
1611
+ "BigNumber, BigNumber": (a, b) => a.compare(b) <= 0,
1612
+ "Unit, Unit": (a, b) => unitCmp(a, b) <= 0
1613
+ });
1614
+ const largerEq = mathTyped("largerEq", {
1615
+ "number, number": (a, b) => a >= b,
1616
+ "bigint, bigint": (a, b) => a >= b,
1617
+ "Fraction, Fraction": (a, b) => a.compare(b) >= 0,
1618
+ "BigNumber, BigNumber": (a, b) => a.compare(b) >= 0,
1619
+ "Unit, Unit": (a, b) => unitCmp(a, b) >= 0
1620
+ });
1621
+ const compare = mathTyped("compare", {
1622
+ "number, number": (a, b) => a > b ? 1 : a < b ? -1 : 0,
1623
+ "bigint, bigint": (a, b) => a > b ? 1 : a < b ? -1 : 0,
1624
+ "Fraction, Fraction": (a, b) => a.compare(b),
1625
+ "BigNumber, BigNumber": (a, b) => a.compare(b),
1626
+ "Unit, Unit": (a, b) => unitCmp(a, b)
1627
+ });
1628
+ const min = mathTyped("min", {
1629
+ "bigint, bigint": (a, b) => a < b ? a : b,
1630
+ "Fraction, Fraction": (a, b) => a.compare(b) < 0 ? a : b,
1631
+ "BigNumber, BigNumber": (a, b) => a.compare(b) < 0 ? a : b,
1632
+ Array: (arr) => {
1633
+ let m = Infinity;
1634
+ for (let i = 0; i < arr.length; i++) m = Math.min(m, arr[i]);
1635
+ return m;
1636
+ },
1637
+ number: (a) => a,
1638
+ "number, number": (a, b) => Math.min(a, b),
1639
+ "number, number, ...number": (a, b, rest) => Math.min(a, b, ...rest),
1640
+ Float64Array: async (a) => {
1641
+ if (computePool.shouldParallelize(a.length, "min")) return (await computePool.min(a)).result;
1642
+ let m = Infinity;
1643
+ for (let i = 0; i < a.length; i++) if (a[i] < m) m = a[i];
1644
+ return m;
1645
+ }
1646
+ });
1647
+ const max = mathTyped("max", {
1648
+ "bigint, bigint": (a, b) => a > b ? a : b,
1649
+ "Fraction, Fraction": (a, b) => a.compare(b) > 0 ? a : b,
1650
+ "BigNumber, BigNumber": (a, b) => a.compare(b) > 0 ? a : b,
1651
+ Array: (arr) => {
1652
+ let m = -Infinity;
1653
+ for (let i = 0; i < arr.length; i++) m = Math.max(m, arr[i]);
1654
+ return m;
1655
+ },
1656
+ number: (a) => a,
1657
+ "number, number": (a, b) => Math.max(a, b),
1658
+ "number, number, ...number": (a, b, rest) => Math.max(a, b, ...rest),
1659
+ Float64Array: async (a) => {
1660
+ if (computePool.shouldParallelize(a.length, "max")) return (await computePool.max(a)).result;
1661
+ let m = -Infinity;
1662
+ for (let i = 0; i < a.length; i++) if (a[i] > m) m = a[i];
1663
+ return m;
1664
+ }
1665
+ });
1666
+ const fsum = mathTyped("fsum", {
1667
+ Array: (arr) => neumaierSum(arr),
1668
+ Float64Array: (a) => neumaierSum(a)
1669
+ });
1670
+ const sum = mathTyped("sum", {
1671
+ Array: (arr) => pairwiseSum(arr),
1672
+ Float64Array: async (a) => {
1673
+ return (await computePool.sum(a)).result;
1674
+ }
1675
+ });
1676
+ const mean = mathTyped("mean", {
1677
+ Array: (arr) => {
1678
+ if (arr.length === 0) return NaN;
1679
+ return pairwiseSum(arr) / arr.length;
1680
+ },
1681
+ Float64Array: async (a) => {
1682
+ return (await computePool.mean(a)).result;
1683
+ }
1684
+ });
1685
+ function varianceFromM2(m2, n, norm) {
1686
+ if (n === 0) return NaN;
1687
+ switch (norm) {
1688
+ case "biased": return m2 / (n + 1);
1689
+ case "uncorrected": return m2 / n;
1690
+ default: return n > 1 ? m2 / (n - 1) : 0;
1691
+ }
1692
+ }
1693
+ function m2OfArray(arr) {
1694
+ return sumSquaredDeviations(arr);
1695
+ }
1696
+ const variance = mathTyped("variance", {
1697
+ Array: (arr) => varianceFromM2(m2OfArray(arr), arr.length, "unbiased"),
1698
+ "Array, string": (arr, norm) => varianceFromM2(m2OfArray(arr), arr.length, norm),
1699
+ Float64Array: async (a) => {
1700
+ return varianceFromM2((await computePool.variance(a)).result.variance * a.length, a.length, "unbiased");
1701
+ },
1702
+ "Float64Array, string": async (a, norm) => {
1703
+ return varianceFromM2((await computePool.variance(a)).result.variance * a.length, a.length, norm);
1704
+ }
1705
+ });
1706
+ const std = mathTyped("std", {
1707
+ Array: (arr) => Math.sqrt(varianceFromM2(m2OfArray(arr), arr.length, "unbiased")),
1708
+ "Array, string": (arr, norm) => Math.sqrt(varianceFromM2(m2OfArray(arr), arr.length, norm)),
1709
+ Float64Array: async (a) => {
1710
+ const result = await computePool.variance(a);
1711
+ return Math.sqrt(varianceFromM2(result.result.variance * a.length, a.length, "unbiased"));
1712
+ },
1713
+ "Float64Array, string": async (a, norm) => {
1714
+ const result = await computePool.variance(a);
1715
+ return Math.sqrt(varianceFromM2(result.result.variance * a.length, a.length, norm));
1716
+ }
1717
+ });
1718
+ const dot = mathTyped("dot", {
1719
+ "Array, Array": (a, b) => {
1720
+ if (a.length !== b.length) throw new Error(`Vector lengths must match: ${a.length} vs ${b.length}`);
1721
+ return pairwiseDot(a, b);
1722
+ },
1723
+ "Float64Array, Float64Array": async (a, b) => {
1724
+ return (await computePool.dot(a, b)).result;
1725
+ }
1726
+ });
1727
+ async function matmul(a, aRows, aCols, b, bCols) {
1728
+ return (await computePool.matmul(a, aRows, aCols, b, bCols)).result;
1729
+ }
1730
+ async function transpose(data, rows, cols) {
1731
+ return (await computePool.transpose(data, rows, cols)).result;
1732
+ }
1733
+ async function matvec(matrix, rows, cols, vector) {
1734
+ return (await computePool.matvec(matrix, rows, cols, vector)).result;
1735
+ }
1736
+ async function outer(a, b) {
1737
+ return (await computePool.outer(a, b)).result;
1738
+ }
1739
+ async function initializePool() {
1740
+ await computePool.initialize();
1741
+ }
1742
+ async function terminatePool() {
1743
+ await computePool.terminate();
1744
+ }
1745
+ function shouldParallelize(elementCount) {
1746
+ return computePool.shouldParallelize(elementCount);
1747
+ }
1748
+ function getComputePool() {
1749
+ return computePool;
1750
+ }
1751
+ const typedArithmetic = {
1752
+ add,
1753
+ subtract,
1754
+ multiply,
1755
+ divide,
1756
+ unaryMinus,
1757
+ unaryPlus,
1758
+ abs,
1759
+ sign,
1760
+ pow: pow$1,
1761
+ sqrt,
1762
+ square,
1763
+ cube,
1764
+ cbrt,
1765
+ nthRoot,
1766
+ exp,
1767
+ log,
1768
+ log10,
1769
+ log2,
1770
+ log1p,
1771
+ expm1,
1772
+ round: round$1,
1773
+ floor,
1774
+ ceil,
1775
+ fix: fix$1,
1776
+ mod,
1777
+ gcd,
1778
+ lcm,
1779
+ xgcd,
1780
+ norm,
1781
+ sinh,
1782
+ cosh,
1783
+ tanh,
1784
+ equal: equal$1,
1785
+ smaller,
1786
+ larger,
1787
+ smallerEq,
1788
+ largerEq,
1789
+ compare,
1790
+ min,
1791
+ max,
1792
+ sum,
1793
+ mean,
1794
+ variance,
1795
+ std,
1796
+ dot,
1797
+ matmul,
1798
+ transpose,
1799
+ matvec,
1800
+ outer,
1801
+ initializePool,
1802
+ terminatePool,
1803
+ shouldParallelize,
1804
+ getComputePool
1805
+ };
1806
+ //#endregion
1807
+ //#region src/typed/trigonometry.ts
1808
+ const sin = mathTyped("sin", {
1809
+ number: (a) => Math.sin(a),
1810
+ Complex: (a) => a.sin(),
1811
+ BigNumber: (a) => a.sin(),
1812
+ Dual: (a) => a.sin(),
1813
+ Float64Array: async (a) => {
1814
+ const wasm = elementwiseUnaryDispatch("sin", a);
1815
+ if (wasm) return wasm;
1816
+ return (await computePool.sin(a)).result;
1817
+ }
1818
+ });
1819
+ const cos = mathTyped("cos", {
1820
+ number: (a) => Math.cos(a),
1821
+ Complex: (a) => a.cos(),
1822
+ BigNumber: (a) => a.cos(),
1823
+ Dual: (a) => a.cos(),
1824
+ Float64Array: async (a) => {
1825
+ const wasm = elementwiseUnaryDispatch("cos", a);
1826
+ if (wasm) return wasm;
1827
+ return (await computePool.cos(a)).result;
1828
+ }
1829
+ });
1830
+ const tan = mathTyped("tan", {
1831
+ number: (a) => Math.tan(a),
1832
+ Complex: (a) => a.tan(),
1833
+ BigNumber: (a) => a.tan(),
1834
+ Dual: (a) => a.tan(),
1835
+ Float64Array: async (a) => {
1836
+ const wasm = elementwiseUnaryDispatch("tan", a);
1837
+ if (wasm) return wasm;
1838
+ return (await computePool.tan(a)).result;
1839
+ }
1840
+ });
1841
+ const csc = mathTyped("csc", {
1842
+ number: (a) => 1 / Math.sin(a),
1843
+ Complex: (a) => a.sin().inverse(),
1844
+ BigNumber: (a) => BigNumber.fromNumber(1).divide(a.sin()),
1845
+ Float64Array: async (a) => {
1846
+ const wasm = elementwiseUnaryDispatch("csc", a);
1847
+ if (wasm) return wasm;
1848
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => 1 / Math.sin(x)")).result;
1849
+ const out = new Float64Array(a.length);
1850
+ for (let i = 0; i < a.length; i++) out[i] = 1 / Math.sin(a[i]);
1851
+ return out;
1852
+ }
1853
+ });
1854
+ const sec = mathTyped("sec", {
1855
+ number: (a) => 1 / Math.cos(a),
1856
+ Complex: (a) => a.cos().inverse(),
1857
+ BigNumber: (a) => BigNumber.fromNumber(1).divide(a.cos()),
1858
+ Float64Array: async (a) => {
1859
+ const wasm = elementwiseUnaryDispatch("sec", a);
1860
+ if (wasm) return wasm;
1861
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => 1 / Math.cos(x)")).result;
1862
+ const out = new Float64Array(a.length);
1863
+ for (let i = 0; i < a.length; i++) out[i] = 1 / Math.cos(a[i]);
1864
+ return out;
1865
+ }
1866
+ });
1867
+ const cot = mathTyped("cot", {
1868
+ number: (a) => 1 / Math.tan(a),
1869
+ Complex: (a) => a.tan().inverse(),
1870
+ BigNumber: (a) => BigNumber.fromNumber(1).divide(a.tan()),
1871
+ Float64Array: async (a) => {
1872
+ const wasm = elementwiseUnaryDispatch("cot", a);
1873
+ if (wasm) return wasm;
1874
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => 1 / Math.tan(x)")).result;
1875
+ const out = new Float64Array(a.length);
1876
+ for (let i = 0; i < a.length; i++) out[i] = 1 / Math.tan(a[i]);
1877
+ return out;
1878
+ }
1879
+ });
1880
+ const asin = mathTyped("asin", {
1881
+ number: (a) => {
1882
+ if (a < -1 || a > 1) return new Complex(a, 0).asin();
1883
+ return Math.asin(a);
1884
+ },
1885
+ Complex: (a) => a.asin(),
1886
+ BigNumber: (a) => a.asin(),
1887
+ Float64Array: async (a) => {
1888
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.asin(x)")).result;
1889
+ const out = new Float64Array(a.length);
1890
+ for (let i = 0; i < a.length; i++) out[i] = Math.asin(a[i]);
1891
+ return out;
1892
+ }
1893
+ });
1894
+ const acos = mathTyped("acos", {
1895
+ number: (a) => {
1896
+ if (a < -1 || a > 1) return new Complex(a, 0).acos();
1897
+ return Math.acos(a);
1898
+ },
1899
+ Complex: (a) => a.acos(),
1900
+ BigNumber: (a) => a.acos(),
1901
+ Float64Array: async (a) => {
1902
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.acos(x)")).result;
1903
+ const out = new Float64Array(a.length);
1904
+ for (let i = 0; i < a.length; i++) out[i] = Math.acos(a[i]);
1905
+ return out;
1906
+ }
1907
+ });
1908
+ const atan = mathTyped("atan", {
1909
+ number: (a) => Math.atan(a),
1910
+ Complex: (a) => a.atan(),
1911
+ BigNumber: (a) => a.atan(),
1912
+ Float64Array: async (a) => {
1913
+ const wasm = elementwiseUnaryDispatch("atan", a);
1914
+ if (wasm) return wasm;
1915
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.atan(x)")).result;
1916
+ const out = new Float64Array(a.length);
1917
+ for (let i = 0; i < a.length; i++) out[i] = Math.atan(a[i]);
1918
+ return out;
1919
+ }
1920
+ });
1921
+ const atan2 = mathTyped("atan2", {
1922
+ "number, number": (y, x) => Math.atan2(y, x),
1923
+ "BigNumber, BigNumber": (y, x) => y.atan2(x)
1924
+ });
1925
+ const acsc = mathTyped("acsc", {
1926
+ number: (a) => Math.asin(1 / a),
1927
+ Complex: (a) => a.inverse().asin(),
1928
+ BigNumber: (a) => BigNumber.fromNumber(1).divide(a).asin()
1929
+ });
1930
+ const asec = mathTyped("asec", {
1931
+ number: (a) => Math.acos(1 / a),
1932
+ Complex: (a) => a.inverse().acos(),
1933
+ BigNumber: (a) => BigNumber.fromNumber(1).divide(a).acos()
1934
+ });
1935
+ const acot = mathTyped("acot", {
1936
+ number: (a) => Math.atan(1 / a),
1937
+ Complex: (a) => a.inverse().atan(),
1938
+ BigNumber: (a) => BigNumber.fromNumber(1).divide(a).atan()
1939
+ });
1940
+ const asinh = mathTyped("asinh", {
1941
+ number: (a) => Math.asinh(a),
1942
+ Complex: (a) => a.asinh(),
1943
+ BigNumber: (a) => a.asinh(),
1944
+ Float64Array: async (a) => {
1945
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.asinh(x)")).result;
1946
+ const out = new Float64Array(a.length);
1947
+ for (let i = 0; i < a.length; i++) out[i] = Math.asinh(a[i]);
1948
+ return out;
1949
+ }
1950
+ });
1951
+ const acosh = mathTyped("acosh", {
1952
+ number: (a) => Math.acosh(a),
1953
+ Complex: (a) => a.acosh(),
1954
+ BigNumber: (a) => a.acosh(),
1955
+ Float64Array: async (a) => {
1956
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.acosh(x)")).result;
1957
+ const out = new Float64Array(a.length);
1958
+ for (let i = 0; i < a.length; i++) out[i] = Math.acosh(a[i]);
1959
+ return out;
1960
+ }
1961
+ });
1962
+ const atanh = mathTyped("atanh", {
1963
+ number: (a) => Math.atanh(a),
1964
+ Complex: (a) => a.atanh(),
1965
+ BigNumber: (a) => a.atanh(),
1966
+ Float64Array: async (a) => {
1967
+ const wasm = elementwiseUnaryDispatch("atanh", a);
1968
+ if (wasm) return wasm;
1969
+ if (computePool.shouldParallelize(a.length)) return (await computePool.applyKernel(a, "(x) => Math.atanh(x)")).result;
1970
+ const out = new Float64Array(a.length);
1971
+ for (let i = 0; i < a.length; i++) out[i] = Math.atanh(a[i]);
1972
+ return out;
1973
+ }
1974
+ });
1975
+ const toRadians = mathTyped("toRadians", { number: (deg) => deg * Math.PI / 180 });
1976
+ const toDegrees = mathTyped("toDegrees", { number: (rad) => rad * 180 / Math.PI });
1977
+ const hypot = mathTyped("hypot", {
1978
+ number: (a) => Math.abs(a),
1979
+ "number, number": (a, b) => Math.hypot(a, b),
1980
+ "number, number, ...number": (a, b, rest) => Math.hypot(a, b, ...rest),
1981
+ Array: (arr) => Math.hypot(...arr)
1982
+ });
1983
+ const typedTrigonometry = {
1984
+ sin,
1985
+ cos,
1986
+ tan,
1987
+ csc,
1988
+ sec,
1989
+ cot,
1990
+ asin,
1991
+ acos,
1992
+ atan,
1993
+ atan2,
1994
+ acsc,
1995
+ asec,
1996
+ acot,
1997
+ asinh,
1998
+ acosh,
1999
+ atanh,
2000
+ toRadians,
2001
+ toDegrees,
2002
+ hypot
2003
+ };
2004
+ //#endregion
2005
+ //#region src/scalar-eval.ts
2006
+ const scalar = createScalarBuilder();
2007
+ var ScalarEvalError = class extends Error {
2008
+ constructor(message) {
2009
+ super(message);
2010
+ this.name = "ScalarEvalError";
2011
+ }
2012
+ };
2013
+ const UNARY = {
2014
+ exp,
2015
+ log,
2016
+ log10,
2017
+ log2,
2018
+ sin,
2019
+ cos,
2020
+ tan,
2021
+ sinh,
2022
+ cosh,
2023
+ tanh,
2024
+ abs
2025
+ };
2026
+ const NUMERIC_LITERAL = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
2027
+ function requireFinite(value, label) {
2028
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ScalarEvalError(`evaluateScalar: '${label}' produced a non-finite value (${String(value)}).`);
2029
+ return value;
2030
+ }
2031
+ function resolveSymbol(name, scope) {
2032
+ if (Object.prototype.hasOwnProperty.call(scope, name)) {
2033
+ const value = scope[name];
2034
+ if (typeof value !== "number") throw new ScalarEvalError(`evaluateScalar: scope['${name}'] is not a number.`);
2035
+ return value;
2036
+ }
2037
+ if (NUMERIC_LITERAL.test(name)) {
2038
+ const literal = Number(name);
2039
+ if (Number.isFinite(literal)) return literal;
2040
+ }
2041
+ throw new ScalarEvalError(`evaluateScalar: symbol '${name}' has no value (not in scope, not a numeric literal).`);
2042
+ }
2043
+ function combine(op, left, right) {
2044
+ switch (op) {
2045
+ case "+": return add(left, right);
2046
+ case "-": return subtract(left, right);
2047
+ case "*": return multiply(left, right);
2048
+ case "/": return divide(left, right);
2049
+ }
2050
+ }
2051
+ function evalOp(op, args, scope) {
2052
+ if (op === "^") {
2053
+ if (args.length !== 2) throw new ScalarEvalError(`evaluateScalar: '^' needs exactly 2 args, got ${args.length}.`);
2054
+ const base = evalNode(args[0], scope);
2055
+ const exponent = evalNode(args[1], scope);
2056
+ return requireFinite(pow$1(base, exponent), "^");
2057
+ }
2058
+ if (args.length === 0) return op === "*" || op === "/" ? 1 : 0;
2059
+ let acc = evalNode(args[0], scope);
2060
+ for (let i = 1; i < args.length; i++) {
2061
+ const right = evalNode(args[i], scope);
2062
+ acc = requireFinite(combine(op, acc, right), op);
2063
+ }
2064
+ return requireFinite(acc, op);
2065
+ }
2066
+ function evalCall(fn, arg) {
2067
+ const impl = UNARY[fn];
2068
+ if (impl === void 0) throw new ScalarEvalError(`evaluateScalar: unknown scalar function '${String(fn)}'.`);
2069
+ return requireFinite(impl(arg), fn);
2070
+ }
2071
+ function evalNode(node, scope) {
2072
+ switch (node.kind) {
2073
+ case "number": return node.value;
2074
+ case "symbol": return resolveSymbol(node.name, scope);
2075
+ case "op": return evalOp(node.op, node.args, scope);
2076
+ case "call": return evalCall(node.fn, evalNode(node.arg, scope));
2077
+ }
2078
+ }
2079
+ function normalizeScope(scope) {
2080
+ if (scope === null || typeof scope !== "object" || Array.isArray(scope)) throw new ScalarEvalError("evaluateScalar: scope must be an object of numbers.");
2081
+ return scope;
2082
+ }
2083
+ function evaluateScalar(node, scope = {}) {
2084
+ const bound = normalizeScope(scope);
2085
+ let canonical;
2086
+ try {
2087
+ canonical = scalar.from(node);
2088
+ } catch (err) {
2089
+ if (err instanceof ScalarBuildError) throw new ScalarEvalError(err.message);
2090
+ throw err;
2091
+ }
2092
+ return evalNode(canonical, bound);
2093
+ }
2094
+ //#endregion
2095
+ //#region src/scalar-compile.ts
2096
+ const LOWERED_UNARY_RULES = {
2097
+ exp: DUAL_UNARY_RULES.exp,
2098
+ log: DUAL_UNARY_RULES.log,
2099
+ log10: DUAL_UNARY_RULES.log10,
2100
+ log2: DUAL_UNARY_RULES.log2,
2101
+ sin: DUAL_UNARY_RULES.sin,
2102
+ cos: DUAL_UNARY_RULES.cos,
2103
+ tan: DUAL_UNARY_RULES.tan,
2104
+ sinh: DUAL_UNARY_RULES.sinh,
2105
+ cosh: DUAL_UNARY_RULES.cosh,
2106
+ tanh: DUAL_UNARY_RULES.tanh,
2107
+ abs: DUAL_UNARY_RULES.abs
2108
+ };
2109
+ function isScalarNode(value) {
2110
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
2111
+ const kind = value.kind;
2112
+ return kind === "number" || kind === "symbol" || kind === "op" || kind === "call";
2113
+ }
2114
+ function assertScalarNode(node, messagePrefix) {
2115
+ if (!isScalarNode(node)) {
2116
+ const kind = node === null || Array.isArray(node) || typeof node !== "object" ? void 0 : node.kind;
2117
+ throw new ScalarEvalError(`${messagePrefix} node kind '${String(kind)}' is not a ScalarNode`);
2118
+ }
2119
+ return node;
2120
+ }
2121
+ function assertNoDuplicateNames(names, messagePrefix) {
2122
+ for (const name of names) if (names.indexOf(name) !== names.lastIndexOf(name)) throw new ScalarEvalError(`${messagePrefix} symbol '${name}' is listed more than once`);
2123
+ }
2124
+ function evalStylePrefix(messagePrefix) {
2125
+ return messagePrefix === "compileScalar:" ? "evaluateScalar:" : messagePrefix;
2126
+ }
2127
+ function copyRegisterGrad(grad, srcReg, destReg, nParams) {
2128
+ const srcBase = srcReg * nParams;
2129
+ const destBase = destReg * nParams;
2130
+ for (let p = 0; p < nParams; p++) grad[destBase + p] = grad[srcBase + p];
2131
+ }
2132
+ function setRegisterGradNaN(grad, reg, nParams) {
2133
+ const base = reg * nParams;
2134
+ for (let p = 0; p < nParams; p++) grad[base + p] = NaN;
2135
+ }
2136
+ function powBasePartial(exp, base) {
2137
+ return exp * Math.pow(base, exp - 1);
2138
+ }
2139
+ function powExpPartial(value, base) {
2140
+ return value * Math.log(base);
2141
+ }
2142
+ function isFloat64ArrayColumn(col) {
2143
+ if (col instanceof Float64Array) return true;
2144
+ return ArrayBuffer.isView(col) && col.constructor.name === "Float64Array";
2145
+ }
2146
+ function applyBinary(op, left, right) {
2147
+ switch (op) {
2148
+ case "+": return left + right;
2149
+ case "-": return left - right;
2150
+ case "*": return left * right;
2151
+ case "/": return left / right;
2152
+ }
2153
+ }
2154
+ function storeChecked(scratch, dest, result, valid) {
2155
+ if (!valid || typeof result !== "number" || !Number.isFinite(result)) {
2156
+ scratch[dest] = NaN;
2157
+ return false;
2158
+ }
2159
+ scratch[dest] = result;
2160
+ return true;
2161
+ }
2162
+ function runRow(tape, scratch, rootReg, columns, params, row, grad, nParams) {
2163
+ let valid = true;
2164
+ if (grad !== void 0 && nParams > 0) grad.fill(0);
2165
+ for (const instr of tape) switch (instr.tag) {
2166
+ case "const":
2167
+ scratch[instr.dest] = instr.value;
2168
+ break;
2169
+ case "column":
2170
+ scratch[instr.dest] = columns[instr.index][row];
2171
+ break;
2172
+ case "param":
2173
+ scratch[instr.dest] = params[instr.index];
2174
+ if (grad !== void 0 && nParams > 0) {
2175
+ const destBase = instr.dest * nParams;
2176
+ for (let p = 0; p < nParams; p++) grad[destBase + p] = p === instr.index ? 1 : 0;
2177
+ }
2178
+ break;
2179
+ case "mov":
2180
+ if (!valid) {
2181
+ scratch[instr.dest] = NaN;
2182
+ if (grad !== void 0 && nParams > 0) setRegisterGradNaN(grad, instr.dest, nParams);
2183
+ break;
2184
+ }
2185
+ valid = storeChecked(scratch, instr.dest, scratch[instr.src], valid);
2186
+ if (grad !== void 0 && nParams > 0) {
2187
+ if (valid) copyRegisterGrad(grad, instr.src, instr.dest, nParams);
2188
+ else setRegisterGradNaN(grad, instr.dest, nParams);
2189
+ }
2190
+ break;
2191
+ case "bin": {
2192
+ if (!valid) {
2193
+ scratch[instr.dest] = NaN;
2194
+ if (grad !== void 0 && nParams > 0) setRegisterGradNaN(grad, instr.dest, nParams);
2195
+ break;
2196
+ }
2197
+ const left = scratch[instr.left];
2198
+ const right = scratch[instr.right];
2199
+ const result = instr.op === "^" ? Math.pow(left, right) : applyBinary(instr.op, left, right);
2200
+ valid = storeChecked(scratch, instr.dest, result, valid);
2201
+ if (grad !== void 0 && nParams > 0) {
2202
+ if (!valid) {
2203
+ setRegisterGradNaN(grad, instr.dest, nParams);
2204
+ break;
2205
+ }
2206
+ const destBase = instr.dest * nParams;
2207
+ const leftBase = instr.left * nParams;
2208
+ const rightBase = instr.right * nParams;
2209
+ if (instr.op === "^") {
2210
+ const base = left;
2211
+ const exp = right;
2212
+ const val = scratch[instr.dest];
2213
+ for (let p = 0; p < nParams; p++) {
2214
+ let g = 0;
2215
+ const dl = grad[leftBase + p];
2216
+ const dr = grad[rightBase + p];
2217
+ if (dl !== 0) {
2218
+ const factor = powBasePartial(exp, base);
2219
+ if (!Number.isFinite(factor)) {
2220
+ valid = false;
2221
+ scratch[instr.dest] = NaN;
2222
+ setRegisterGradNaN(grad, instr.dest, nParams);
2223
+ break;
2224
+ }
2225
+ g += dl * factor;
2226
+ }
2227
+ if (dr !== 0) {
2228
+ const factor = powExpPartial(val, base);
2229
+ if (!Number.isFinite(factor)) {
2230
+ valid = false;
2231
+ scratch[instr.dest] = NaN;
2232
+ setRegisterGradNaN(grad, instr.dest, nParams);
2233
+ break;
2234
+ }
2235
+ g += dr * factor;
2236
+ }
2237
+ grad[destBase + p] = g;
2238
+ }
2239
+ } else for (let p = 0; p < nParams; p++) {
2240
+ const gl = grad[leftBase + p];
2241
+ const gr = grad[rightBase + p];
2242
+ switch (instr.op) {
2243
+ case "+":
2244
+ grad[destBase + p] = gl + gr;
2245
+ break;
2246
+ case "-":
2247
+ grad[destBase + p] = gl - gr;
2248
+ break;
2249
+ case "*":
2250
+ grad[destBase + p] = gl * right + left * gr;
2251
+ break;
2252
+ case "/": {
2253
+ const denom = right * right;
2254
+ grad[destBase + p] = (gl * right - left * gr) / denom;
2255
+ break;
2256
+ }
2257
+ }
2258
+ }
2259
+ }
2260
+ break;
2261
+ }
2262
+ case "unary": {
2263
+ if (!valid) {
2264
+ scratch[instr.dest] = NaN;
2265
+ if (grad !== void 0 && nParams > 0) setRegisterGradNaN(grad, instr.dest, nParams);
2266
+ break;
2267
+ }
2268
+ const x = scratch[instr.arg];
2269
+ const rule = LOWERED_UNARY_RULES[instr.fn];
2270
+ const result = rule.primal(x);
2271
+ valid = storeChecked(scratch, instr.dest, result, valid);
2272
+ if (grad !== void 0 && nParams > 0) {
2273
+ if (!valid) {
2274
+ setRegisterGradNaN(grad, instr.dest, nParams);
2275
+ break;
2276
+ }
2277
+ const destBase = instr.dest * nParams;
2278
+ const argBase = instr.arg * nParams;
2279
+ const y = scratch[instr.dest];
2280
+ for (let p = 0; p < nParams; p++) {
2281
+ const al = grad[argBase + p];
2282
+ if (al === 0) {
2283
+ grad[destBase + p] = 0;
2284
+ continue;
2285
+ }
2286
+ const d = rule.deriv(x, y);
2287
+ if (!Number.isFinite(d)) {
2288
+ valid = false;
2289
+ scratch[instr.dest] = NaN;
2290
+ setRegisterGradNaN(grad, instr.dest, nParams);
2291
+ break;
2292
+ }
2293
+ grad[destBase + p] = al * d;
2294
+ }
2295
+ }
2296
+ break;
2297
+ }
2298
+ }
2299
+ return {
2300
+ value: scratch[rootReg],
2301
+ valid
2302
+ };
2303
+ }
2304
+ function allocReg(ctx) {
2305
+ return ctx.nextReg++;
2306
+ }
2307
+ function bindSymbol(ctx, name, dest) {
2308
+ const inVars = ctx.variables.indexOf(name);
2309
+ const inParams = ctx.parameters.indexOf(name);
2310
+ const inConsts = Object.prototype.hasOwnProperty.call(ctx.constants, name);
2311
+ if ((inVars >= 0 ? 1 : 0) + (inParams >= 0 ? 1 : 0) + (inConsts ? 1 : 0) >= 2) throw new ScalarEvalError(`${ctx.messagePrefix} symbol '${name}' is listed more than once`);
2312
+ if (inParams >= 0) {
2313
+ ctx.tape.push({
2314
+ tag: "param",
2315
+ dest,
2316
+ index: inParams
2317
+ });
2318
+ return;
2319
+ }
2320
+ if (inVars >= 0) {
2321
+ ctx.tape.push({
2322
+ tag: "column",
2323
+ dest,
2324
+ index: inVars
2325
+ });
2326
+ return;
2327
+ }
2328
+ if (inConsts) {
2329
+ const value = ctx.constants[name];
2330
+ if (typeof value !== "number") throw new ScalarEvalError(`${ctx.messagePrefix} constant '${name}' is not a number`);
2331
+ ctx.tape.push({
2332
+ tag: "const",
2333
+ dest,
2334
+ value
2335
+ });
2336
+ return;
2337
+ }
2338
+ if (NUMERIC_LITERAL.test(name)) {
2339
+ const literal = Number(name);
2340
+ if (Number.isFinite(literal)) {
2341
+ ctx.tape.push({
2342
+ tag: "const",
2343
+ dest,
2344
+ value: literal
2345
+ });
2346
+ return;
2347
+ }
2348
+ }
2349
+ throw new ScalarEvalError(`${evalStylePrefix(ctx.messagePrefix)} symbol '${name}' has no value (not in scope, not a numeric literal).`);
2350
+ }
2351
+ function compileNode(ctx, node) {
2352
+ const canonical = assertScalarNode(node, ctx.messagePrefix);
2353
+ const dest = allocReg(ctx);
2354
+ switch (canonical.kind) {
2355
+ case "number":
2356
+ ctx.tape.push({
2357
+ tag: "const",
2358
+ dest,
2359
+ value: canonical.value
2360
+ });
2361
+ ctx.rootReg = dest;
2362
+ return dest;
2363
+ case "symbol":
2364
+ bindSymbol(ctx, canonical.name, dest);
2365
+ ctx.rootReg = dest;
2366
+ return dest;
2367
+ case "call": {
2368
+ if (!Object.prototype.hasOwnProperty.call(LOWERED_UNARY_RULES, canonical.fn)) throw new ScalarEvalError(`${evalStylePrefix(ctx.messagePrefix)} unknown scalar function '${String(canonical.fn)}'.`);
2369
+ const argReg = compileNode(ctx, canonical.arg);
2370
+ ctx.tape.push({
2371
+ tag: "unary",
2372
+ dest,
2373
+ fn: canonical.fn,
2374
+ arg: argReg
2375
+ });
2376
+ ctx.rootReg = dest;
2377
+ return dest;
2378
+ }
2379
+ case "op": {
2380
+ const { op, args } = canonical;
2381
+ if (op === "^") {
2382
+ if (args.length !== 2) throw new ScalarEvalError(`${evalStylePrefix(ctx.messagePrefix)} '^' needs exactly 2 args, got ${args.length}.`);
2383
+ const left = compileNode(ctx, args[0]);
2384
+ const right = compileNode(ctx, args[1]);
2385
+ ctx.tape.push({
2386
+ tag: "bin",
2387
+ dest,
2388
+ op: "^",
2389
+ left,
2390
+ right
2391
+ });
2392
+ ctx.rootReg = dest;
2393
+ return dest;
2394
+ }
2395
+ if (args.length === 0) {
2396
+ const value = op === "*" || op === "/" ? 1 : 0;
2397
+ ctx.tape.push({
2398
+ tag: "const",
2399
+ dest,
2400
+ value
2401
+ });
2402
+ ctx.rootReg = dest;
2403
+ return dest;
2404
+ }
2405
+ if (args.length === 1) {
2406
+ const src = compileNode(ctx, args[0]);
2407
+ if (src !== dest) ctx.tape.push({
2408
+ tag: "mov",
2409
+ dest,
2410
+ src
2411
+ });
2412
+ ctx.rootReg = dest;
2413
+ return dest;
2414
+ }
2415
+ let acc = compileNode(ctx, args[0]);
2416
+ for (let i = 1; i < args.length; i++) {
2417
+ const right = compileNode(ctx, args[i]);
2418
+ const stepDest = i === args.length - 1 ? dest : acc;
2419
+ ctx.tape.push({
2420
+ tag: "bin",
2421
+ dest: stepDest,
2422
+ op,
2423
+ left: acc,
2424
+ right
2425
+ });
2426
+ acc = stepDest;
2427
+ }
2428
+ ctx.rootReg = dest;
2429
+ return dest;
2430
+ }
2431
+ }
2432
+ }
2433
+ function checkCompileParams(params, parameters, messagePrefix) {
2434
+ const nParams = parameters.length;
2435
+ if (params === void 0) {
2436
+ if (nParams > 0) throw new ScalarEvalError(`${messagePrefix} expected ${nParams} parameters, got 0`);
2437
+ return [];
2438
+ }
2439
+ if (params.length !== nParams) throw new ScalarEvalError(`${messagePrefix} expected ${nParams} parameters, got ${params.length}`);
2440
+ for (let i = 0; i < nParams; i++) if (typeof params[i] !== "number") throw new ScalarEvalError(`${messagePrefix} parameter ${i} is not a number`);
2441
+ return params;
2442
+ }
2443
+ function compileRowCount(columns, variables, messagePrefix) {
2444
+ const nVars = variables.length;
2445
+ if (columns.length !== nVars) throw new ScalarEvalError(`${messagePrefix} expected ${nVars} columns, got ${columns.length}`);
2446
+ for (let i = 0; i < columns.length; i++) if (!isFloat64ArrayColumn(columns[i])) throw new ScalarEvalError(`${messagePrefix} column ${i} must be a Float64Array`);
2447
+ if (nVars === 0) return 1;
2448
+ const n = columns[0].length;
2449
+ for (let i = 1; i < columns.length; i++) if (columns[i].length !== n) throw new ScalarEvalError(`${messagePrefix} columns must have the same length`);
2450
+ return n;
2451
+ }
2452
+ function evaluateScalarTape(tape, rootReg, nRegs, columns, variables, params, parameters, messagePrefix, out, scratch = new Float64Array(nRegs)) {
2453
+ const n = compileRowCount(columns, variables, messagePrefix);
2454
+ const boundParams = checkCompileParams(params, parameters, messagePrefix);
2455
+ let values;
2456
+ if (out !== void 0) {
2457
+ if (out.length !== n) throw new ScalarEvalError(`${messagePrefix} out length ${out.length} does not match row count ${n}`);
2458
+ values = out;
2459
+ } else values = new Float64Array(n);
2460
+ const valid = new Uint8Array(n);
2461
+ let allValid = true;
2462
+ for (let row = 0; row < n; row++) {
2463
+ const { value, valid: rowValid } = runRow(tape, scratch, rootReg, columns, boundParams, row, void 0, 0);
2464
+ values[row] = rowValid ? value : NaN;
2465
+ valid[row] = rowValid ? 1 : 0;
2466
+ if (!rowValid) allValid = false;
2467
+ }
2468
+ return {
2469
+ values,
2470
+ valid,
2471
+ allValid
2472
+ };
2473
+ }
2474
+ function buildTape(node, options, messagePrefix) {
2475
+ const canonical = assertScalarNode(node, messagePrefix);
2476
+ const variables = options.variables.slice();
2477
+ const parameters = (options.parameters ?? []).slice();
2478
+ const constants = options.constants ?? {};
2479
+ assertNoDuplicateNames(variables, messagePrefix);
2480
+ assertNoDuplicateNames(parameters, messagePrefix);
2481
+ const ctx = {
2482
+ variables,
2483
+ parameters,
2484
+ constants,
2485
+ messagePrefix,
2486
+ tape: [],
2487
+ nextReg: 0,
2488
+ rootReg: 0
2489
+ };
2490
+ compileNode(ctx, canonical);
2491
+ return {
2492
+ tape: ctx.tape,
2493
+ rootReg: ctx.rootReg,
2494
+ nRegs: ctx.nextReg,
2495
+ variables,
2496
+ parameters
2497
+ };
2498
+ }
2499
+ function compileScalar(node, options) {
2500
+ const messagePrefix = "compileScalar:";
2501
+ const { tape, rootReg, nRegs, variables, parameters } = buildTape(node, options, messagePrefix);
2502
+ const scratch = new Float64Array(nRegs);
2503
+ return {
2504
+ variables,
2505
+ parameters,
2506
+ evaluate(columns, params, out) {
2507
+ return evaluateScalarTape(tape, rootReg, nRegs, columns, variables, params ?? [], parameters, messagePrefix, out, scratch);
2508
+ },
2509
+ evaluateRow(row, params) {
2510
+ const nVars = variables.length;
2511
+ if (row.length !== nVars) throw new ScalarEvalError(`compileScalar: expected ${nVars} row entries, got ${row.length}`);
2512
+ for (let i = 0; i < nVars; i++) if (typeof row[i] !== "number") throw new ScalarEvalError(`compileScalar: row entry ${i} is not a number`);
2513
+ const boundParams = checkCompileParams(params, parameters, messagePrefix);
2514
+ const columns = [];
2515
+ for (let i = 0; i < nVars; i++) {
2516
+ const col = /* @__PURE__ */ new Float64Array(1);
2517
+ col[0] = row[i];
2518
+ columns.push(col);
2519
+ }
2520
+ const { value, valid: rowValid } = runRow(tape, scratch, rootReg, columns, boundParams, 0, void 0, 0);
2521
+ if (!rowValid) throw new ScalarEvalError("compileScalar: row produced a non-finite value.");
2522
+ return value;
2523
+ }
2524
+ };
2525
+ }
2526
+ function compileScalarGradient(node, options) {
2527
+ const messagePrefix = "compileScalarGradient:";
2528
+ const { tape, rootReg, nRegs, variables, parameters } = buildTape(node, options, messagePrefix);
2529
+ const scratch = new Float64Array(nRegs);
2530
+ const nParams = parameters.length;
2531
+ const gradScratch = nParams > 0 ? new Float64Array(nRegs * nParams) : /* @__PURE__ */ new Float64Array(0);
2532
+ return {
2533
+ variables,
2534
+ parameters,
2535
+ evaluate(columns, params, out) {
2536
+ const n = compileRowCount(columns, variables, messagePrefix);
2537
+ const boundParams = checkCompileParams(params, parameters, messagePrefix);
2538
+ let values;
2539
+ if (out?.values !== void 0) {
2540
+ if (out.values.length !== n) throw new ScalarEvalError(`${messagePrefix} out values length ${out.values.length} does not match row count ${n}`);
2541
+ values = out.values;
2542
+ } else values = new Float64Array(n);
2543
+ let grad;
2544
+ const gradLen = n * nParams;
2545
+ if (out?.grad !== void 0) {
2546
+ if (out.grad.length !== gradLen) throw new ScalarEvalError(`${messagePrefix} out grad length ${out.grad.length} does not match ${gradLen}`);
2547
+ grad = out.grad;
2548
+ } else grad = new Float64Array(gradLen);
2549
+ const valid = new Uint8Array(n);
2550
+ let allValid = true;
2551
+ const rootBase = rootReg * nParams;
2552
+ for (let row = 0; row < n; row++) {
2553
+ const { value, valid: rowValid } = runRow(tape, scratch, rootReg, columns, boundParams, row, nParams > 0 ? gradScratch : void 0, nParams);
2554
+ values[row] = rowValid ? value : NaN;
2555
+ valid[row] = rowValid ? 1 : 0;
2556
+ const gradRow = row * nParams;
2557
+ if (rowValid && nParams > 0) for (let p = 0; p < nParams; p++) grad[gradRow + p] = gradScratch[rootBase + p];
2558
+ else if (nParams > 0) for (let p = 0; p < nParams; p++) grad[gradRow + p] = NaN;
2559
+ if (!rowValid) allValid = false;
2560
+ }
2561
+ return {
2562
+ values,
2563
+ valid,
2564
+ allValid,
2565
+ grad
2566
+ };
2567
+ }
2568
+ };
2569
+ }
2570
+ //#endregion
2571
+ //#region src/scalar-batch-task.ts
2572
+ const SCALAR_BATCH_MESSAGE_PREFIX = "compileScalar:";
2573
+ function runScalarBatchTask(task) {
2574
+ const rows = [];
2575
+ for (const item of task.items) {
2576
+ const batch = evaluateScalarTape(item.tape, item.rootReg, item.nRegs, task.columns, task.variables, item.params, item.parameters, SCALAR_BATCH_MESSAGE_PREFIX);
2577
+ rows.push({
2578
+ candidateIndex: item.candidateIndex,
2579
+ values: batch.values,
2580
+ valid: batch.valid,
2581
+ allValid: batch.allValid
2582
+ });
2583
+ }
2584
+ return { rows };
2585
+ }
2586
+ //#endregion
2587
+ export { log1p as $, abs as A, xgcd as At, exp as B, wasmPolicyAllows as Bt, hypot as C, tanh as Ct, toDegrees as D, unaryMinus as Dt, tan as E, typedArithmetic as Et, cosh as F, getWasm as Ft, gcd as G, createMatrixBridge as Gt, fix$1 as H, loadWasm as Ht, cube as I, isAsWasm as It, larger as J, getComputePool as K, euclidSnap as Kt, divide as L, makeUnaryArrayDispatch as Lt, cbrt as M, elementwiseUnaryDispatch as Mt, ceil as N, asReadReturnedF64 as Nt, toRadians as O, unaryPlus as Ot, compare as P, asReadReturnedI32 as Pt, log10 as Q, dot as R, withAsF64 as Rt, csc as S, sum as St, sin as T, transpose as Tt, floor as U, MathJSDenseMatrix as Ut, expm1 as V, isWasmLoaded as Vt, fsum as W, MathJSSparseMatrix as Wt, lcm as X, largerEq as Y, log as Z, atan as _, smallerEq as _t, compileScalarGradient as a, min as at, cos as b, std as bt, evaluateScalar as c, norm as ct, acosh as d, pow$1 as dt, log2 as et, acot as f, round$1 as ft, asinh as g, smaller as gt, asin as h, sinh as ht, compileScalar as i, mean as it, add as j, elementwiseChainDispatch as jt, typedTrigonometry as k, variance as kt, scalar as l, nthRoot as lt, asec as m, sign as mt, runScalarBatchTask as n, matvec as nt, NUMERIC_LITERAL as o, mod as ot, acsc as p, shouldParallelize as pt, initializePool as q, buildTape as r, max as rt, ScalarEvalError as s, multiply as st, SCALAR_BATCH_MESSAGE_PREFIX as t, matmul as tt, acos as u, outer as ut, atan2 as v, sqrt as vt, sec as w, terminatePool as wt, cot as x, subtract as xt, atanh as y, square as yt, equal$1 as z, withAsI32 as zt };