@danielsimonjr/mathts-matrix 0.1.2 → 0.1.4

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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import * as _danielsimonjr_mathts_parallel from '@danielsimonjr/mathts-parallel';
2
1
  import { ComputePool, ComputePoolConfig } from '@danielsimonjr/mathts-parallel';
3
2
  import * as typed_function from 'typed-function';
4
3
 
@@ -192,167 +191,165 @@ declare abstract class Matrix<T = number> {
192
191
  declare function isMatrix<T = number>(value: unknown): value is Matrix<T>;
193
192
 
194
193
  /**
195
- * Sparse Matrix Implementation (CSR Format)
196
- *
197
- * Compressed Sparse Row (CSR) format sparse matrix for efficient storage
198
- * and operations on matrices with many zero elements.
194
+ * Dense Matrix Implementation
199
195
  *
200
- * CSR stores:
201
- * - values: Non-zero values in row-major order
202
- * - colIndices: Column index for each non-zero value
203
- * - rowPointers: Index into values/colIndices where each row starts
196
+ * Row-major dense matrix backed by Float64Array for efficient storage
197
+ * and operations. Supports views (slices without copying) where possible.
204
198
  *
205
199
  * @packageDocumentation
206
200
  */
207
201
 
208
202
  /**
209
- * Sparse matrix using Compressed Sparse Row (CSR) format
203
+ * Dense matrix implementation using Float64Array
210
204
  *
211
- * Efficient for:
212
- * - Row slicing and iteration
213
- * - Sparse matrix-vector multiplication
214
- * - Matrices with many zeros (typically < 10% non-zero)
205
+ * Data is stored in row-major order for cache-friendly row access.
206
+ * All operations return new matrices (immutable API).
215
207
  */
216
- declare class SparseMatrix extends Matrix<number> {
217
- readonly type: "SparseMatrix";
208
+ declare class DenseMatrix extends Matrix<number> {
209
+ readonly type: "DenseMatrix";
218
210
  readonly rows: number;
219
211
  readonly cols: number;
220
212
  /**
221
- * Non-zero values in row-major order
213
+ * Internal data storage (row-major Float64Array)
222
214
  */
223
- private readonly _data;
215
+ private readonly data;
224
216
  /**
225
- * Column indices for each non-zero value
217
+ * Whether this matrix is a view into another matrix's data
226
218
  */
227
- private readonly _colIndices;
219
+ private readonly isView;
228
220
  /**
229
- * Row pointers: rowPointers[i] = index of first non-zero in row i
230
- * rowPointers[rows] = total number of non-zeros (nnz)
221
+ * Offset into data array (for views)
231
222
  */
232
- private readonly _rowPointers;
223
+ private readonly offset;
233
224
  /**
234
- * Create a sparse matrix from CSR components
225
+ * Stride between rows (for views)
226
+ */
227
+ private readonly rowStride;
228
+ /**
229
+ * Create a new DenseMatrix
235
230
  *
236
231
  * @param rows - Number of rows
237
232
  * @param cols - Number of columns
238
- * @param values - Non-zero values
239
- * @param colIndices - Column index for each value
240
- * @param rowPointers - Row start indices
233
+ * @param data - Optional initial data (row-major order)
241
234
  */
242
- constructor(rows: number, cols: number, values: Float64Array | number[], colIndices: Int32Array | number[], rowPointers: Int32Array | number[]);
235
+ constructor(rows: number, cols: number, data?: Float64Array | number[] | number[][], viewConfig?: {
236
+ isView: boolean;
237
+ offset: number;
238
+ rowStride: number;
239
+ });
243
240
  /**
244
- * Create a sparse matrix from a dense matrix
245
- *
246
- * @param dense - Dense matrix to convert
247
- * @param dropTolerance - Values below this threshold are treated as zero
241
+ * Create a matrix from a nested array
248
242
  */
249
- static fromDense(dense: DenseMatrix, dropTolerance?: number): SparseMatrix;
243
+ static fromArray(arr: number[][]): DenseMatrix;
250
244
  /**
251
- * Create a sparse matrix from coordinate (COO) format
252
- *
253
- * @param rows - Number of rows
254
- * @param cols - Number of columns
255
- * @param entries - Array of {row, col, value} entries
245
+ * Create a matrix from a flat array with specified dimensions
256
246
  */
257
- static fromCOO(rows: number, cols: number, entries: Array<{
258
- row: number;
259
- col: number;
260
- value: number;
261
- }>): SparseMatrix;
247
+ static fromFlat(rows: number, cols: number, data: number[]): DenseMatrix;
262
248
  /**
263
- * Create a zero sparse matrix
249
+ * Create a zero matrix
264
250
  */
265
- static zeros(rows: number, cols: number): SparseMatrix;
251
+ static zeros(rows: number, cols: number): DenseMatrix;
266
252
  /**
267
- * Create a sparse identity matrix
253
+ * Create a matrix filled with ones
268
254
  */
269
- static identity(n: number): SparseMatrix;
255
+ static ones(rows: number, cols: number): DenseMatrix;
270
256
  /**
271
- * Create a sparse diagonal matrix
257
+ * Create an identity matrix
272
258
  */
273
- static diag(values: number[]): SparseMatrix;
259
+ static identity(n: number): DenseMatrix;
274
260
  /**
275
- * Number of non-zero elements
261
+ * Create a diagonal matrix from values
276
262
  */
277
- get nnz(): number;
263
+ static diag(values: number[]): DenseMatrix;
278
264
  /**
279
- * Sparsity: fraction of zero elements
265
+ * Create a matrix filled with a constant value
280
266
  */
281
- get sparsity(): number;
267
+ static fill(rows: number, cols: number, value: number): DenseMatrix;
282
268
  /**
283
- * Density: fraction of non-zero elements
269
+ * Create a matrix with random values in [0, 1)
284
270
  */
285
- get density(): number;
271
+ static random(rows: number, cols: number): DenseMatrix;
286
272
  /**
287
- * Get element at (row, col) - O(log(nnz_in_row)) for sorted columns
273
+ * Get element at (row, col)
274
+ * O(1) access time
288
275
  */
289
276
  get(row: number, col: number): number;
290
277
  /**
291
- * Set element at (row, col) - returns new matrix (immutable)
278
+ * Set element at (row, col) - returns new matrix
292
279
  */
293
- set(row: number, col: number, value: number): SparseMatrix;
280
+ set(row: number, col: number, value: number): DenseMatrix;
294
281
  /**
295
- * Get a row as a sparse 1×n matrix
282
+ * Get the raw Float64Array data (copy if view, reference otherwise)
296
283
  */
297
- row(index: number): SparseMatrix;
284
+ private toFlatFloat64Array;
298
285
  /**
299
- * Get a column as a sparse m×1 matrix
286
+ * Get a row as a 1×n matrix (view, no copy)
300
287
  */
301
- column(index: number): SparseMatrix;
288
+ row(index: number): DenseMatrix;
289
+ /**
290
+ * Get a column as an m×1 matrix (copy, since data is row-major)
291
+ */
292
+ column(index: number): DenseMatrix;
302
293
  /**
303
294
  * Get a submatrix
304
295
  */
305
- slice(spec: SliceSpec): SparseMatrix;
296
+ slice(spec: SliceSpec): DenseMatrix;
306
297
  /**
307
298
  * Get the diagonal elements
308
299
  */
309
- diagonal(k?: number): SparseMatrix;
300
+ diagonal(k?: number): DenseMatrix;
310
301
  /**
311
- * Sparse matrix addition
302
+ * Matrix addition
312
303
  */
313
- add(other: Matrix<number>): SparseMatrix;
314
- private addSparse;
304
+ add(other: Matrix<number>): DenseMatrix;
315
305
  /**
316
- * Sparse matrix subtraction
306
+ * Matrix subtraction
317
307
  */
318
- subtract(other: Matrix<number>): SparseMatrix;
308
+ subtract(other: Matrix<number>): DenseMatrix;
319
309
  /**
320
310
  * Element-wise multiplication (Hadamard product)
321
311
  */
322
- multiplyElementwise(other: Matrix<number>): SparseMatrix;
312
+ multiplyElementwise(other: Matrix<number>): DenseMatrix;
323
313
  /**
324
- * Sparse matrix multiplication
314
+ * Matrix multiplication
325
315
  */
326
- multiply(other: Matrix<number>): SparseMatrix;
327
- private multiplySparse;
316
+ multiply(other: Matrix<number>): DenseMatrix;
328
317
  /**
329
318
  * Scalar multiplication
330
319
  */
331
- scale(scalar: number): SparseMatrix;
320
+ scale(scalar: number): DenseMatrix;
332
321
  /**
333
- * Sparse matrix transpose
322
+ * Matrix transpose
334
323
  */
335
- transpose(): SparseMatrix;
324
+ transpose(): DenseMatrix;
336
325
  /**
337
326
  * Negate all elements
338
327
  */
339
- negate(): SparseMatrix;
328
+ negate(): DenseMatrix;
340
329
  /**
341
330
  * Sum of all elements
342
331
  */
343
332
  sum(): number;
344
333
  /**
345
- * Frobenius norm
334
+ * Mean of all elements
335
+ */
336
+ mean(): number;
337
+ /**
338
+ * Minimum element
339
+ */
340
+ min(): number;
341
+ /**
342
+ * Maximum element
343
+ */
344
+ max(): number;
345
+ /**
346
+ * Frobenius norm (sqrt of sum of squared elements)
346
347
  */
347
348
  norm(): number;
348
349
  /**
349
350
  * Trace (sum of diagonal elements)
350
351
  */
351
352
  trace(): number;
352
- /**
353
- * Convert to dense matrix
354
- */
355
- toDense(): DenseMatrix;
356
353
  /**
357
354
  * Convert to nested array
358
355
  */
@@ -361,209 +358,213 @@ declare class SparseMatrix extends Matrix<number> {
361
358
  * Convert to flat array (row-major)
362
359
  */
363
360
  toFlatArray(): number[];
361
+ /**
362
+ * Get the underlying Float64Array (copy)
363
+ */
364
+ toFloat64Array(): Float64Array;
364
365
  /**
365
366
  * Clone the matrix
366
367
  */
367
- clone(): SparseMatrix;
368
+ clone(): DenseMatrix;
368
369
  /**
369
- * Get the CSR components
370
+ * Convert to sparse matrix (CSR format)
371
+ *
372
+ * This is a synchronous conversion that creates a SparseMatrix
373
+ * containing only the non-zero elements of this matrix.
374
+ *
375
+ * @param dropTolerance - Values below this threshold are treated as zero
376
+ * @returns SparseMatrix representation (typed as the `Matrix` base — the
377
+ * `SparseMatrix` subtype is loaded lazily to avoid an import cycle)
370
378
  */
371
- getCSR(): {
372
- values: Float64Array;
373
- colIndices: Int32Array;
374
- rowPointers: Int32Array;
375
- };
379
+ toSparse(dropTolerance?: number): Matrix;
376
380
  /**
377
- * Iterate over non-zero entries
381
+ * Iterate over entries with indices
378
382
  */
379
383
  entries(): IterableIterator<MatrixEntry<number>>;
380
384
  /**
381
- * Iterate over non-zero values
385
+ * Iterate over values (row-major)
382
386
  */
383
387
  values(): IterableIterator<number>;
384
388
  /**
385
- * Iterate over all values (including zeros, row-major)
386
- */
387
- allValues(): IterableIterator<number>;
388
- /**
389
- * Support for...of iteration (iterates over non-zero values)
389
+ * Support for...of iteration (iterates over values)
390
390
  */
391
391
  [Symbol.iterator](): IterableIterator<number>;
392
392
  /**
393
- * Apply a function to each non-zero element
393
+ * Apply a function to each element
394
394
  */
395
- mapNonZeros(fn: (value: number, row: number, col: number) => number): SparseMatrix;
395
+ map(fn: (value: number, row: number, col: number) => number): DenseMatrix;
396
396
  /**
397
- * Apply a function to each element (including zeros)
398
- * Warning: This may create a dense result
397
+ * Apply a function to each element (no return, for side effects)
399
398
  */
400
- map(fn: (value: number, row: number, col: number) => number): SparseMatrix;
399
+ forEach(fn: (value: number, row: number, col: number) => void): void;
401
400
  }
402
401
  /**
403
- * Type guard for SparseMatrix
402
+ * Type guard for DenseMatrix
404
403
  */
405
- declare function isSparseMatrix(value: unknown): value is SparseMatrix;
404
+ declare function isDenseMatrix(value: unknown): value is DenseMatrix;
406
405
 
407
406
  /**
408
- * Dense Matrix Implementation
407
+ * Sparse Matrix Implementation (CSR Format)
409
408
  *
410
- * Row-major dense matrix backed by Float64Array for efficient storage
411
- * and operations. Supports views (slices without copying) where possible.
409
+ * Compressed Sparse Row (CSR) format sparse matrix for efficient storage
410
+ * and operations on matrices with many zero elements.
411
+ *
412
+ * CSR stores:
413
+ * - values: Non-zero values in row-major order
414
+ * - colIndices: Column index for each non-zero value
415
+ * - rowPointers: Index into values/colIndices where each row starts
412
416
  *
413
417
  * @packageDocumentation
414
418
  */
415
419
 
416
420
  /**
417
- * Dense matrix implementation using Float64Array
421
+ * Sparse matrix using Compressed Sparse Row (CSR) format
418
422
  *
419
- * Data is stored in row-major order for cache-friendly row access.
420
- * All operations return new matrices (immutable API).
423
+ * Efficient for:
424
+ * - Row slicing and iteration
425
+ * - Sparse matrix-vector multiplication
426
+ * - Matrices with many zeros (typically < 10% non-zero)
421
427
  */
422
- declare class DenseMatrix extends Matrix<number> {
423
- readonly type: "DenseMatrix";
428
+ declare class SparseMatrix extends Matrix<number> {
429
+ readonly type: "SparseMatrix";
424
430
  readonly rows: number;
425
431
  readonly cols: number;
426
432
  /**
427
- * Internal data storage (row-major Float64Array)
428
- */
429
- private readonly data;
430
- /**
431
- * Whether this matrix is a view into another matrix's data
433
+ * Non-zero values in row-major order
432
434
  */
433
- private readonly isView;
435
+ private readonly _data;
434
436
  /**
435
- * Offset into data array (for views)
437
+ * Column indices for each non-zero value
436
438
  */
437
- private readonly offset;
439
+ private readonly _colIndices;
438
440
  /**
439
- * Stride between rows (for views)
441
+ * Row pointers: rowPointers[i] = index of first non-zero in row i
442
+ * rowPointers[rows] = total number of non-zeros (nnz)
440
443
  */
441
- private readonly rowStride;
444
+ private readonly _rowPointers;
442
445
  /**
443
- * Create a new DenseMatrix
446
+ * Create a sparse matrix from CSR components
444
447
  *
445
448
  * @param rows - Number of rows
446
449
  * @param cols - Number of columns
447
- * @param data - Optional initial data (row-major order)
450
+ * @param values - Non-zero values
451
+ * @param colIndices - Column index for each value
452
+ * @param rowPointers - Row start indices
448
453
  */
449
- constructor(rows: number, cols: number, data?: Float64Array | number[] | number[][], viewConfig?: {
450
- isView: boolean;
451
- offset: number;
452
- rowStride: number;
453
- });
454
+ constructor(rows: number, cols: number, values: Float64Array | number[], colIndices: Int32Array | number[], rowPointers: Int32Array | number[]);
454
455
  /**
455
- * Create a matrix from a nested array
456
+ * Create a sparse matrix from a dense matrix
457
+ *
458
+ * @param dense - Dense matrix to convert
459
+ * @param dropTolerance - Values below this threshold are treated as zero
456
460
  */
457
- static fromArray(arr: number[][]): DenseMatrix;
461
+ static fromDense(dense: DenseMatrix, dropTolerance?: number): SparseMatrix;
458
462
  /**
459
- * Create a matrix from a flat array with specified dimensions
463
+ * Create a sparse matrix from coordinate (COO) format
464
+ *
465
+ * @param rows - Number of rows
466
+ * @param cols - Number of columns
467
+ * @param entries - Array of {row, col, value} entries
460
468
  */
461
- static fromFlat(rows: number, cols: number, data: number[]): DenseMatrix;
469
+ static fromCOO(rows: number, cols: number, entries: Array<{
470
+ row: number;
471
+ col: number;
472
+ value: number;
473
+ }>): SparseMatrix;
462
474
  /**
463
- * Create a zero matrix
475
+ * Create a zero sparse matrix
464
476
  */
465
- static zeros(rows: number, cols: number): DenseMatrix;
477
+ static zeros(rows: number, cols: number): SparseMatrix;
466
478
  /**
467
- * Create a matrix filled with ones
479
+ * Create a sparse identity matrix
468
480
  */
469
- static ones(rows: number, cols: number): DenseMatrix;
481
+ static identity(n: number): SparseMatrix;
470
482
  /**
471
- * Create an identity matrix
483
+ * Create a sparse diagonal matrix
472
484
  */
473
- static identity(n: number): DenseMatrix;
485
+ static diag(values: number[]): SparseMatrix;
474
486
  /**
475
- * Create a diagonal matrix from values
487
+ * Number of non-zero elements
476
488
  */
477
- static diag(values: number[]): DenseMatrix;
489
+ get nnz(): number;
478
490
  /**
479
- * Create a matrix filled with a constant value
491
+ * Sparsity: fraction of zero elements
480
492
  */
481
- static fill(rows: number, cols: number, value: number): DenseMatrix;
493
+ get sparsity(): number;
482
494
  /**
483
- * Create a matrix with random values in [0, 1)
495
+ * Density: fraction of non-zero elements
484
496
  */
485
- static random(rows: number, cols: number): DenseMatrix;
497
+ get density(): number;
486
498
  /**
487
- * Get element at (row, col)
488
- * O(1) access time
499
+ * Get element at (row, col) - O(log(nnz_in_row)) for sorted columns
489
500
  */
490
501
  get(row: number, col: number): number;
491
502
  /**
492
- * Set element at (row, col) - returns new matrix
493
- */
494
- set(row: number, col: number, value: number): DenseMatrix;
495
- /**
496
- * Get the raw Float64Array data (copy if view, reference otherwise)
503
+ * Set element at (row, col) - returns new matrix (immutable)
497
504
  */
498
- private toFlatFloat64Array;
505
+ set(row: number, col: number, value: number): SparseMatrix;
499
506
  /**
500
- * Get a row as a 1×n matrix (view, no copy)
507
+ * Get a row as a sparse 1×n matrix
501
508
  */
502
- row(index: number): DenseMatrix;
509
+ row(index: number): SparseMatrix;
503
510
  /**
504
- * Get a column as an m×1 matrix (copy, since data is row-major)
511
+ * Get a column as a sparse m×1 matrix
505
512
  */
506
- column(index: number): DenseMatrix;
513
+ column(index: number): SparseMatrix;
507
514
  /**
508
515
  * Get a submatrix
509
516
  */
510
- slice(spec: SliceSpec): DenseMatrix;
517
+ slice(spec: SliceSpec): SparseMatrix;
511
518
  /**
512
519
  * Get the diagonal elements
513
520
  */
514
- diagonal(k?: number): DenseMatrix;
521
+ diagonal(k?: number): SparseMatrix;
515
522
  /**
516
- * Matrix addition
523
+ * Sparse matrix addition
517
524
  */
518
- add(other: Matrix<number>): DenseMatrix;
525
+ add(other: Matrix<number>): SparseMatrix;
526
+ private addSparse;
519
527
  /**
520
- * Matrix subtraction
528
+ * Sparse matrix subtraction
521
529
  */
522
- subtract(other: Matrix<number>): DenseMatrix;
530
+ subtract(other: Matrix<number>): SparseMatrix;
523
531
  /**
524
532
  * Element-wise multiplication (Hadamard product)
525
533
  */
526
- multiplyElementwise(other: Matrix<number>): DenseMatrix;
534
+ multiplyElementwise(other: Matrix<number>): SparseMatrix;
527
535
  /**
528
- * Matrix multiplication
536
+ * Sparse matrix multiplication
529
537
  */
530
- multiply(other: Matrix<number>): DenseMatrix;
538
+ multiply(other: Matrix<number>): SparseMatrix;
539
+ private multiplySparse;
531
540
  /**
532
541
  * Scalar multiplication
533
542
  */
534
- scale(scalar: number): DenseMatrix;
543
+ scale(scalar: number): SparseMatrix;
535
544
  /**
536
- * Matrix transpose
545
+ * Sparse matrix transpose
537
546
  */
538
- transpose(): DenseMatrix;
547
+ transpose(): SparseMatrix;
539
548
  /**
540
549
  * Negate all elements
541
550
  */
542
- negate(): DenseMatrix;
551
+ negate(): SparseMatrix;
543
552
  /**
544
553
  * Sum of all elements
545
554
  */
546
555
  sum(): number;
547
556
  /**
548
- * Mean of all elements
549
- */
550
- mean(): number;
551
- /**
552
- * Minimum element
553
- */
554
- min(): number;
555
- /**
556
- * Maximum element
557
- */
558
- max(): number;
559
- /**
560
- * Frobenius norm (sqrt of sum of squared elements)
557
+ * Frobenius norm
561
558
  */
562
559
  norm(): number;
563
560
  /**
564
561
  * Trace (sum of diagonal elements)
565
562
  */
566
563
  trace(): number;
564
+ /**
565
+ * Convert to dense matrix
566
+ */
567
+ toDense(): DenseMatrix;
567
568
  /**
568
569
  * Convert to nested array
569
570
  */
@@ -572,49 +573,48 @@ declare class DenseMatrix extends Matrix<number> {
572
573
  * Convert to flat array (row-major)
573
574
  */
574
575
  toFlatArray(): number[];
575
- /**
576
- * Get the underlying Float64Array (copy)
577
- */
578
- toFloat64Array(): Float64Array;
579
576
  /**
580
577
  * Clone the matrix
581
578
  */
582
- clone(): DenseMatrix;
579
+ clone(): SparseMatrix;
583
580
  /**
584
- * Convert to sparse matrix (CSR format)
585
- *
586
- * This is a synchronous conversion that creates a SparseMatrix
587
- * containing only the non-zero elements of this matrix.
588
- *
589
- * @param dropTolerance - Values below this threshold are treated as zero
590
- * @returns SparseMatrix representation
581
+ * Get the CSR components
591
582
  */
592
- toSparse(dropTolerance?: number): SparseMatrix;
583
+ getCSR(): {
584
+ values: Float64Array;
585
+ colIndices: Int32Array;
586
+ rowPointers: Int32Array;
587
+ };
593
588
  /**
594
- * Iterate over entries with indices
589
+ * Iterate over non-zero entries
595
590
  */
596
591
  entries(): IterableIterator<MatrixEntry<number>>;
597
592
  /**
598
- * Iterate over values (row-major)
593
+ * Iterate over non-zero values
599
594
  */
600
595
  values(): IterableIterator<number>;
601
596
  /**
602
- * Support for...of iteration (iterates over values)
597
+ * Iterate over all values (including zeros, row-major)
598
+ */
599
+ allValues(): IterableIterator<number>;
600
+ /**
601
+ * Support for...of iteration (iterates over non-zero values)
603
602
  */
604
603
  [Symbol.iterator](): IterableIterator<number>;
605
604
  /**
606
- * Apply a function to each element
605
+ * Apply a function to each non-zero element
607
606
  */
608
- map(fn: (value: number, row: number, col: number) => number): DenseMatrix;
607
+ mapNonZeros(fn: (value: number, row: number, col: number) => number): SparseMatrix;
609
608
  /**
610
- * Apply a function to each element (no return, for side effects)
609
+ * Apply a function to each element (including zeros)
610
+ * Warning: This may create a dense result
611
611
  */
612
- forEach(fn: (value: number, row: number, col: number) => void): void;
612
+ map(fn: (value: number, row: number, col: number) => number): SparseMatrix;
613
613
  }
614
614
  /**
615
- * Type guard for DenseMatrix
615
+ * Type guard for SparseMatrix
616
616
  */
617
- declare function isDenseMatrix(value: unknown): value is DenseMatrix;
617
+ declare function isSparseMatrix(value: unknown): value is SparseMatrix;
618
618
 
619
619
  /**
620
620
  * Matrix Backend Interface
@@ -629,7 +629,7 @@ declare function isDenseMatrix(value: unknown): value is DenseMatrix;
629
629
  /**
630
630
  * Backend type identifier
631
631
  */
632
- type BackendType = 'js' | 'wasm' | 'gpu' | 'parallel';
632
+ type BackendType = 'js' | 'wasm' | 'rust-wasm' | 'gpu' | 'parallel';
633
633
  /**
634
634
  * Backend selection hints
635
635
  */
@@ -854,6 +854,96 @@ declare class JSBackend implements MatrixBackend {
854
854
  */
855
855
  declare const jsBackend: JSBackend;
856
856
 
857
+ /**
858
+ * Stub type declarations for workerpool.
859
+ * The actual workerpool package ships raw .ts sources without pre-built .d.ts files.
860
+ * This stub prevents TypeScript from diving into the raw source during type-checking.
861
+ */
862
+ declare module 'workerpool' {
863
+ export interface ExecOptions<T = unknown> {
864
+ on?: (payload: unknown) => void;
865
+ transfer?: Transferable[];
866
+ metadata?: T;
867
+ }
868
+
869
+ export interface PoolStats {
870
+ totalWorkers: number;
871
+ busyWorkers: number;
872
+ idleWorkers: number;
873
+ pendingTasks: number;
874
+ activeTasks: number;
875
+ }
876
+
877
+ export interface PoolOptions {
878
+ minWorkers?: number | 'max';
879
+ maxWorkers?: number;
880
+ maxQueueSize?: number;
881
+ workerType?: 'auto' | 'web' | 'process' | 'thread';
882
+ queueStrategy?: 'fifo' | 'lifo';
883
+ script?: string;
884
+ workerTerminateTimeout?: number;
885
+ forkArgs?: string[];
886
+ forkOpts?: Record<string, unknown>;
887
+ workerOpts?: Record<string, unknown>;
888
+ workerThreadOpts?: Record<string, unknown>;
889
+ emitStdStreams?: boolean;
890
+ onCreateWorker?: (arg: Record<string, unknown>) => Record<string, unknown> | void;
891
+ onTerminateWorker?: (arg: Record<string, unknown>) => void;
892
+ debugPortStart?: number;
893
+ }
894
+
895
+ export interface WorkerpoolPromise<T, E = unknown> extends Promise<T> {
896
+ readonly resolved: boolean;
897
+ readonly rejected: boolean;
898
+ readonly pending: boolean;
899
+ cancel(): this;
900
+ timeout(delay: number): this;
901
+ }
902
+
903
+ export type WorkerProxy<T extends Record<string, (...args: unknown[]) => unknown>> = {
904
+ [K in keyof T]: (...args: Parameters<T[K]>) => WorkerpoolPromise<ReturnType<T[K]>>;
905
+ };
906
+
907
+ export class Pool {
908
+ constructor(script?: string | PoolOptions, options?: PoolOptions);
909
+ exec<T>(
910
+ method: string | ((...args: unknown[]) => T),
911
+ params?: unknown[],
912
+ options?: ExecOptions
913
+ ): WorkerpoolPromise<T>;
914
+ proxy<T extends Record<string, (...args: unknown[]) => unknown>>(): Promise<WorkerProxy<T>>;
915
+ stats(): PoolStats;
916
+ terminate(force?: boolean, timeout?: number): Promise<void>;
917
+ }
918
+
919
+ export interface TransferDescriptor<T = unknown> {
920
+ message: T;
921
+ transfer: Transferable[];
922
+ }
923
+
924
+ export class Transfer<T = unknown> {
925
+ message: T;
926
+ transfer: Transferable[];
927
+ constructor(message: T, transfer: Transferable[]);
928
+ }
929
+
930
+ export class CancellationError extends Error {}
931
+ export class TimeoutError extends Error {}
932
+ export class TerminateError extends Error {}
933
+
934
+ export function pool(script?: string | PoolOptions, options?: PoolOptions): Pool;
935
+
936
+ export function worker(
937
+ methods?: Record<string, (...args: unknown[]) => unknown>,
938
+ options?: {
939
+ onTerminate?: (code: number | undefined) => void | PromiseLike<void>;
940
+ abortListenerTimeout?: number;
941
+ }
942
+ ): void;
943
+
944
+ export function workerEmit(payload: unknown): void;
945
+ }
946
+
857
947
  /**
858
948
  * Configuration for ParallelBackend
859
949
  */
@@ -960,7 +1050,7 @@ declare class ParallelBackend {
960
1050
  /**
961
1051
  * Get pool statistics
962
1052
  */
963
- getStats(): _danielsimonjr_mathts_parallel.PoolStats;
1053
+ getStats(): undefined;
964
1054
  private checkDimensionsMatch;
965
1055
  private checkMultiplyDimensions;
966
1056
  }
@@ -1032,10 +1122,50 @@ declare function clearFeatureCache(): void;
1032
1122
  declare function getCachedFeatures(): WasmFeatures | null;
1033
1123
 
1034
1124
  /**
1035
- * WASM Matrix Backend
1036
- *
1037
- * Implements MatrixBackend using WebAssembly for accelerated operations.
1038
- * Falls back to JSBackend when WASM is unavailable or for small matrices.
1125
+ * WASM Matrix Backend (AssemblyScript)
1126
+ *
1127
+ * Implements MatrixBackend using the AssemblyScript-compiled WebAssembly
1128
+ * module (`lib/wasm/mathts-as.wasm`, ~42 KB). Falls back to JSBackend when
1129
+ * the WASM module is unavailable or for small matrices.
1130
+ *
1131
+ * ABI:
1132
+ * The AS module exports a managed runtime (`__new` / `__pin` / `__unpin` /
1133
+ * `__collect`) and its matrix/array functions accept managed `Float64Array`
1134
+ * *header* pointers — NOT raw flat-memory pointers. A typed-array header is
1135
+ * a 12-byte block at some offset that stores (buffer, buffer, byteLength).
1136
+ *
1137
+ * To call e.g. `matrix_add(a, b, result)` from JS, we have to:
1138
+ * 1. `__new(byteLength, 1)` — allocate the data buffer (id=1 = ArrayBuffer)
1139
+ * 2. `__pin(buffer)` — pin so it survives GC while building header
1140
+ * 3. `__new(12, 5)` — allocate the Float64Array header (id=5)
1141
+ * 4. Write [buffer, buffer, byteLength] into the header
1142
+ * 5. Copy caller data into the buffer
1143
+ * 6. `__unpin(buffer)` — the header now owns the buffer reference
1144
+ *
1145
+ * The Rust artifact has no managed runtime and uses a completely different
1146
+ * ABI (camelCase exports, flat-memory raw pointers); for that backend, use
1147
+ * `RustWASMBackend` (from `./RustWASMBackend.ts`).
1148
+ *
1149
+ * Naming map (Rust ↔ AssemblyScript) — for cross-backend reference:
1150
+ *
1151
+ * Op Rust (camelCase, flat ptrs) AS (snake_case, header refs)
1152
+ * ------------------ --------------------------------- -------------------------------
1153
+ * add add(aPtr,bPtr,n,resPtr) matrix_add(a,b,result)
1154
+ * subtract subtract(aPtr,bPtr,n,resPtr) matrix_sub(a,b,result)
1155
+ * multiplyElementwise simdMulF64(aPtr,bPtr,resPtr,n) matrix_mul_elementwise(a,b,result)
1156
+ * divideElementwise (none) matrix_div_elementwise(a,b,result)
1157
+ * scale simdScaleF64(aPtr,s,resPtr,n) matrix_scale(a,scalar,result)
1158
+ * abs simdAbsF64(aPtr,resPtr,n) array_abs(a,result)
1159
+ * negate simdScaleF64(aPtr,-1,resPtr,n) matrix_neg(a,result)
1160
+ * multiply multiplyDense(a,r,c,b,r,c,res) matrix_multiply(a,aRows,aCols,b,bCols,result)
1161
+ * transpose transpose(a,r,c,res) matrix_transpose(a,rows,cols,result)
1162
+ * sum simdSumF64(aPtr,n) array_sum(a)
1163
+ * norm simdNormF64(aPtr,n) array_norm(a)
1164
+ * dot dotProduct(aPtr,bPtr,n) array_dot(a,b)
1165
+ *
1166
+ * AssemblyScript has no LU / QR / Cholesky / inverse / determinant exports,
1167
+ * so those operations fall back to the JS implementation. The Rust backend
1168
+ * has them — route those calls through `RustWASMBackend` if you need WASM.
1039
1169
  *
1040
1170
  * @packageDocumentation
1041
1171
  */
@@ -1046,16 +1176,18 @@ declare function getCachedFeatures(): WasmFeatures | null;
1046
1176
  interface WASMBackendConfig {
1047
1177
  /** Minimum elements to use WASM (default: 100) */
1048
1178
  minElements?: number;
1049
- /** Path to WASM file */
1179
+ /** Path to WASM file (defaults to the AS artifact, `lib/wasm/mathts-as.wasm`) */
1050
1180
  wasmPath?: string;
1051
- /** Enable SIMD optimizations when available */
1181
+ /** Enable SIMD code paths if the AS module exposes them (currently a no-op
1182
+ * — AS export surface does not include `simd*` ops; kept for API stability). */
1052
1183
  useSIMD?: boolean;
1053
1184
  }
1054
1185
  /**
1055
- * WASM Backend for matrix operations
1186
+ * WASM Backend for matrix operations (AssemblyScript path).
1056
1187
  *
1057
- * Uses WebAssembly for accelerated matrix operations with SIMD support.
1058
- * Automatically falls back to JavaScript for small matrices or when WASM unavailable.
1188
+ * For the Rust path use `RustWASMBackend`. Both implement `MatrixBackend`
1189
+ * and report different `type` discriminants ('wasm' vs 'rust-wasm') so that
1190
+ * `BackendManager` can route operations to the correct one.
1059
1191
  */
1060
1192
  declare class WASMBackend implements MatrixBackend {
1061
1193
  readonly type: BackendType;
@@ -1063,23 +1195,27 @@ declare class WASMBackend implements MatrixBackend {
1063
1195
  private wasmModule;
1064
1196
  private features;
1065
1197
  private initPromise;
1198
+ /** Pooled allocations — see `AsAllocCache` for rationale. */
1199
+ private allocCache;
1066
1200
  constructor(config?: WASMBackendConfig);
1067
- /**
1068
- * Check if WASM is available in the current environment
1069
- */
1070
1201
  isAvailable(): boolean;
1071
- /**
1072
- * Initialize the WASM backend
1073
- */
1074
1202
  initialize(): Promise<void>;
1075
1203
  private doInitialize;
1076
1204
  /**
1077
- * Check if operation should use WASM
1205
+ * Resolve the path to the AssemblyScript artifact (`lib/wasm/mathts-as.wasm`).
1206
+ *
1207
+ * On Windows, `URL.pathname` returns "/C:/foo/bar.wasm" which fs.readFile
1208
+ * interprets as drive-relative ("C:\C:\foo\..."). `fileURLToPath` does the
1209
+ * platform-correct conversion.
1078
1210
  */
1079
- private shouldUseWasm;
1211
+ private resolveAsWasmPath;
1080
1212
  /**
1081
- * Get detected WASM features
1213
+ * Compile + instantiate the AssemblyScript WASM artifact. Each
1214
+ * WASMBackend instance owns its own instance — this is intentional so
1215
+ * tests and the Rust backend can coexist in the same process.
1082
1216
  */
1217
+ private loadAsModule;
1218
+ private shouldUseWasm;
1083
1219
  getFeatures(): WasmFeatures | null;
1084
1220
  add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
1085
1221
  subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
@@ -1094,40 +1230,24 @@ declare class WASMBackend implements MatrixBackend {
1094
1230
  sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
1095
1231
  norm(a: DenseMatrix): number;
1096
1232
  dot(a: DenseMatrix, b: DenseMatrix): number;
1097
- /**
1098
- * LU Decomposition using WASM
1099
- */
1100
1233
  luDecomposition(a: DenseMatrix): Promise<{
1101
1234
  lu: DenseMatrix;
1102
1235
  perm: Int32Array;
1103
1236
  singular: boolean;
1104
1237
  }>;
1105
1238
  private luDecompositionJS;
1106
- /**
1107
- * QR Decomposition using WASM
1108
- */
1109
1239
  qrDecomposition(a: DenseMatrix): Promise<{
1110
1240
  q: DenseMatrix;
1111
1241
  r: DenseMatrix;
1112
1242
  }>;
1113
1243
  private qrDecompositionJS;
1114
- /**
1115
- * Matrix inversion using LU decomposition
1116
- */
1117
1244
  inverse(a: DenseMatrix): Promise<{
1118
1245
  inverse: DenseMatrix;
1119
1246
  singular: boolean;
1120
1247
  }>;
1121
1248
  private inverseJS;
1122
- /**
1123
- * Compute matrix determinant using LU decomposition
1124
- */
1125
1249
  determinantWasm(a: DenseMatrix): Promise<number>;
1126
1250
  private determinantJS;
1127
- /**
1128
- * Cholesky Decomposition using WASM
1129
- * For symmetric positive-definite matrices: A = L * L^T
1130
- */
1131
1251
  choleskyDecomposition(a: DenseMatrix): Promise<{
1132
1252
  l: DenseMatrix;
1133
1253
  positiveDefinite: boolean;
@@ -1143,11 +1263,11 @@ declare class WASMBackend implements MatrixBackend {
1143
1263
  getConfig(): Required<WASMBackendConfig>;
1144
1264
  }
1145
1265
  /**
1146
- * Global WASM backend instance
1266
+ * Global WASM backend instance (AssemblyScript path)
1147
1267
  */
1148
1268
  declare const wasmBackend: WASMBackend;
1149
1269
  /**
1150
- * Create a WASM backend with custom configuration
1270
+ * Create a WASM backend (AssemblyScript path) with custom configuration
1151
1271
  */
1152
1272
  declare function createWASMBackend(config?: WASMBackendConfig): WASMBackend;
1153
1273
 
@@ -1893,170 +2013,489 @@ declare class GPUBackend {
1893
2013
  */
1894
2014
  add(a: Float32Array, b: Float32Array, rows: number, cols: number): Promise<Float32Array>;
1895
2015
  /**
1896
- * Multiply two matrices
2016
+ * Multiply two matrices
2017
+ */
2018
+ matmul(a: Float32Array, b: Float32Array, M: number, K: number, N: number): Promise<Float32Array>;
2019
+ /**
2020
+ * Transpose a matrix
2021
+ */
2022
+ transpose(a: Float32Array, rows: number, cols: number): Promise<Float32Array>;
2023
+ /**
2024
+ * Scale a matrix by a scalar
2025
+ */
2026
+ scale(a: Float32Array, scalar: number): Promise<Float32Array>;
2027
+ /**
2028
+ * Get backend statistics
2029
+ */
2030
+ getStats(): {
2031
+ status: GPUBackendStatus;
2032
+ capabilities: GPUCapabilities | null;
2033
+ bufferPool: {
2034
+ totalBuffers: number;
2035
+ inUseBuffers: number;
2036
+ cachedBuffers: number;
2037
+ } | null;
2038
+ shaders: {
2039
+ cachedShaders: number;
2040
+ cachedPipelines: number;
2041
+ } | null;
2042
+ };
2043
+ /**
2044
+ * Destroy the backend
2045
+ */
2046
+ destroy(): void;
2047
+ }
2048
+ /**
2049
+ * Get the global GPU backend
2050
+ */
2051
+ declare function getGlobalGPUBackend(): GPUBackend;
2052
+ /**
2053
+ * Initialize the global GPU backend
2054
+ */
2055
+ declare function initializeGlobalGPUBackend(options?: GPUBackendOptions): Promise<boolean>;
2056
+ /**
2057
+ * Destroy the global GPU backend
2058
+ */
2059
+ declare function destroyGlobalGPUBackend(): void;
2060
+
2061
+ /**
2062
+ * GPU Matrix Backend Adapter
2063
+ *
2064
+ * Adapts GPUBackend to implement the MatrixBackend interface,
2065
+ * enabling seamless integration with the backend selection system.
2066
+ *
2067
+ * @packageDocumentation
2068
+ */
2069
+
2070
+ /**
2071
+ * Configuration for GPU Matrix Backend
2072
+ */
2073
+ interface GPUMatrixBackendConfig {
2074
+ /** Minimum elements to use GPU (default: 65536 = 256x256) */
2075
+ minElements?: number;
2076
+ /** Use global GPU backend instance */
2077
+ useGlobalBackend?: boolean;
2078
+ /** GPU backend options */
2079
+ gpuOptions?: GPUBackendOptions;
2080
+ /** Fall back to JS on GPU errors */
2081
+ fallbackOnError?: boolean;
2082
+ }
2083
+ /**
2084
+ * GPU Matrix Backend
2085
+ *
2086
+ * Implements MatrixBackend interface using WebGPU compute shaders.
2087
+ * Provides significant acceleration for large matrices.
2088
+ *
2089
+ * @example
2090
+ * ```typescript
2091
+ * const gpu = new GPUMatrixBackend();
2092
+ * await gpu.initialize();
2093
+ *
2094
+ * const result = gpu.multiply(matrixA, matrixB);
2095
+ * ```
2096
+ */
2097
+ declare class GPUMatrixBackend implements MatrixBackend {
2098
+ readonly type: BackendType;
2099
+ private config;
2100
+ private backend;
2101
+ private capabilities;
2102
+ private initPromise;
2103
+ private _available;
2104
+ constructor(config?: GPUMatrixBackendConfig);
2105
+ /**
2106
+ * Check if GPU is available in the current environment
2107
+ */
2108
+ isAvailable(): boolean;
2109
+ /**
2110
+ * Initialize the GPU backend
2111
+ */
2112
+ initialize(): Promise<void>;
2113
+ private doInitialize;
2114
+ /**
2115
+ * Check if operation should use GPU
2116
+ */
2117
+ private shouldUseGPU;
2118
+ /**
2119
+ * Execute GPU operation with fallback
2120
+ */
2121
+ private executeWithFallback;
2122
+ /**
2123
+ * Get GPU capabilities
2124
+ */
2125
+ getCapabilities(): GPUCapabilities | null;
2126
+ /**
2127
+ * Get backend statistics
2128
+ */
2129
+ getStats(): ReturnType<GPUBackend['getStats']> | null;
2130
+ add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2131
+ /**
2132
+ * Async add operation using GPU
2133
+ */
2134
+ addAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
2135
+ subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2136
+ multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2137
+ divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2138
+ scale(a: DenseMatrix, scalar: number): DenseMatrix;
2139
+ /**
2140
+ * Async scale operation using GPU
2141
+ */
2142
+ scaleAsync(a: DenseMatrix, scalar: number): Promise<DenseMatrix>;
2143
+ abs(a: DenseMatrix): DenseMatrix;
2144
+ negate(a: DenseMatrix): DenseMatrix;
2145
+ multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2146
+ /**
2147
+ * Async matrix multiplication using GPU
2148
+ */
2149
+ multiplyAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
2150
+ transpose(a: DenseMatrix): DenseMatrix;
2151
+ /**
2152
+ * Async transpose using GPU
2153
+ */
2154
+ transposeAsync(a: DenseMatrix): Promise<DenseMatrix>;
2155
+ sum(a: DenseMatrix): number;
2156
+ sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
2157
+ norm(a: DenseMatrix): number;
2158
+ dot(a: DenseMatrix, b: DenseMatrix): number;
2159
+ /**
2160
+ * Update configuration
2161
+ */
2162
+ updateConfig(config: Partial<GPUMatrixBackendConfig>): void;
2163
+ /**
2164
+ * Get current configuration
2165
+ */
2166
+ getConfig(): Required<GPUMatrixBackendConfig>;
2167
+ /**
2168
+ * Destroy the backend
2169
+ */
2170
+ destroy(): void;
2171
+ }
2172
+ /**
2173
+ * Global GPU matrix backend instance
2174
+ */
2175
+ declare const gpuMatrixBackend: GPUMatrixBackend;
2176
+ /**
2177
+ * Create a GPU matrix backend with custom configuration
2178
+ */
2179
+ declare function createGPUMatrixBackend(config?: GPUMatrixBackendConfig): GPUMatrixBackend;
2180
+
2181
+ /**
2182
+ * Rust WASM Matrix Backend
2183
+ *
2184
+ * Implements MatrixBackend using the Rust-compiled WebAssembly module (648 KB).
2185
+ * Designed for heavy operations: large matrix multiply (faer), FFT (rustfft),
2186
+ * eigendecomposition, sparse algebra, and SIMD-accelerated array operations.
2187
+ *
2188
+ * This backend sits alongside the existing WASMBackend (AssemblyScript) and
2189
+ * is selected by BackendManager for large matrices and heavy operations.
2190
+ *
2191
+ * Memory model:
2192
+ * Uses a bump allocator on the JS side to write data into WASM linear
2193
+ * memory. The allocator is reset between operations (batch-free pattern).
2194
+ * This avoids the overhead of per-allocation malloc/free calls.
2195
+ *
2196
+ * @packageDocumentation
2197
+ */
2198
+
2199
+ /**
2200
+ * Rust WASM Backend configuration
2201
+ */
2202
+ interface RustWASMBackendConfig {
2203
+ /** Minimum elements to use Rust WASM (default: 1000) */
2204
+ minElements?: number;
2205
+ /** Path to the Rust WASM binary */
2206
+ wasmPath?: string;
2207
+ }
2208
+ /**
2209
+ * Rust WASM Backend for matrix operations.
2210
+ *
2211
+ * Uses the Rust WASM module for heavy computation, with automatic
2212
+ * fallback to JSBackend when the module is unavailable or for small matrices.
2213
+ *
2214
+ * The backend registers as type 'wasm' so it can serve as a drop-in
2215
+ * replacement or complement to the AssemblyScript WASMBackend. When both
2216
+ * are needed, use BackendManager's operation-specific routing.
2217
+ */
2218
+ declare class RustWASMBackend implements MatrixBackend {
2219
+ /**
2220
+ * Backend type identifier.
2221
+ * Uses 'rust-wasm' to distinguish from the AssemblyScript WASMBackend.
2222
+ */
2223
+ readonly type: BackendType;
2224
+ private config;
2225
+ private exports;
2226
+ private initPromise;
2227
+ constructor(config?: RustWASMBackendConfig);
2228
+ /**
2229
+ * Check if WebAssembly is available in the current environment.
2230
+ */
2231
+ isAvailable(): boolean;
2232
+ /**
2233
+ * Initialize the Rust WASM backend.
2234
+ * Loads the WASM binary and caches the exports.
2235
+ */
2236
+ initialize(): Promise<void>;
2237
+ private doInitialize;
2238
+ /**
2239
+ * Whether to use Rust WASM for this operation size.
2240
+ */
2241
+ private shouldUseRustWasm;
2242
+ /**
2243
+ * Whether the Rust WASM module is loaded and ready.
2244
+ */
2245
+ get isRustLoaded(): boolean;
2246
+ add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2247
+ subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2248
+ multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2249
+ divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2250
+ scale(a: DenseMatrix, scalar: number): DenseMatrix;
2251
+ abs(a: DenseMatrix): DenseMatrix;
2252
+ negate(a: DenseMatrix): DenseMatrix;
2253
+ multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2254
+ transpose(a: DenseMatrix): DenseMatrix;
2255
+ sum(a: DenseMatrix): number;
2256
+ sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
2257
+ norm(a: DenseMatrix): number;
2258
+ dot(a: DenseMatrix, b: DenseMatrix): number;
2259
+ /**
2260
+ * LU Decomposition using Rust WASM.
2261
+ */
2262
+ luDecomposition(a: DenseMatrix): Promise<{
2263
+ lu: DenseMatrix;
2264
+ perm: Int32Array;
2265
+ singular: boolean;
2266
+ }>;
2267
+ /**
2268
+ * Eigenvalue decomposition for symmetric matrices using Rust WASM.
1897
2269
  */
1898
- matmul(a: Float32Array, b: Float32Array, M: number, K: number, N: number): Promise<Float32Array>;
2270
+ eigsSymmetric(a: DenseMatrix, precision?: number): Promise<{
2271
+ eigenvalues: Float64Array;
2272
+ eigenvectors: DenseMatrix;
2273
+ iterations: number;
2274
+ }>;
1899
2275
  /**
1900
- * Transpose a matrix
2276
+ * Matrix inversion using Rust WASM.
1901
2277
  */
1902
- transpose(a: Float32Array, rows: number, cols: number): Promise<Float32Array>;
2278
+ inverse(a: DenseMatrix): Promise<{
2279
+ inverse: DenseMatrix;
2280
+ singular: boolean;
2281
+ }>;
1903
2282
  /**
1904
- * Scale a matrix by a scalar
2283
+ * FFT using Rust WASM (rustfft).
2284
+ * Data is interleaved complex: [re0, im0, re1, im1, ...].
1905
2285
  */
1906
- scale(a: Float32Array, scalar: number): Promise<Float32Array>;
2286
+ fft(data: Float64Array, n: number, inverse?: boolean): Float64Array;
1907
2287
  /**
1908
- * Get backend statistics
2288
+ * Update configuration.
1909
2289
  */
1910
- getStats(): {
1911
- status: GPUBackendStatus;
1912
- capabilities: GPUCapabilities | null;
1913
- bufferPool: {
1914
- totalBuffers: number;
1915
- inUseBuffers: number;
1916
- cachedBuffers: number;
1917
- } | null;
1918
- shaders: {
1919
- cachedShaders: number;
1920
- cachedPipelines: number;
1921
- } | null;
1922
- };
2290
+ updateConfig(config: Partial<RustWASMBackendConfig>): void;
1923
2291
  /**
1924
- * Destroy the backend
2292
+ * Get current configuration.
1925
2293
  */
1926
- destroy(): void;
2294
+ getConfig(): Required<RustWASMBackendConfig>;
1927
2295
  }
1928
2296
  /**
1929
- * Get the global GPU backend
1930
- */
1931
- declare function getGlobalGPUBackend(): GPUBackend;
1932
- /**
1933
- * Initialize the global GPU backend
2297
+ * Global Rust WASM backend instance
1934
2298
  */
1935
- declare function initializeGlobalGPUBackend(options?: GPUBackendOptions): Promise<boolean>;
2299
+ declare const rustWasmBackend: RustWASMBackend;
1936
2300
  /**
1937
- * Destroy the global GPU backend
2301
+ * Create a Rust WASM backend with custom configuration
1938
2302
  */
1939
- declare function destroyGlobalGPUBackend(): void;
2303
+ declare function createRustWASMBackend(config?: RustWASMBackendConfig): RustWASMBackend;
1940
2304
 
1941
2305
  /**
1942
- * GPU Matrix Backend Adapter
2306
+ * Rust WASM Loader
1943
2307
  *
1944
- * Adapts GPUBackend to implement the MatrixBackend interface,
1945
- * enabling seamless integration with the backend selection system.
2308
+ * Loads and manages the Rust-compiled WebAssembly module (648 KB).
2309
+ * The Rust WASM provides heavy computation: matrix multiply (faer),
2310
+ * FFT (rustfft), eigendecomposition, sparse algebra, statistics (statrs),
2311
+ * and SIMD-accelerated array operations.
2312
+ *
2313
+ * Memory model:
2314
+ * The Rust WASM uses `#[no_mangle] extern "C"` raw exports with
2315
+ * a linear memory model. Unlike the AssemblyScript WASM, there is
2316
+ * no managed GC heap (`__new`/`__pin`/`__unpin`/`__collect`).
2317
+ * Instead, JavaScript writes data directly into WASM linear memory
2318
+ * at computed offsets and passes those offsets as pointers.
1946
2319
  *
1947
2320
  * @packageDocumentation
1948
2321
  */
1949
-
1950
2322
  /**
1951
- * Configuration for GPU Matrix Backend
2323
+ * Typed interface for Rust WASM exports.
2324
+ *
2325
+ * This is a subset of the full export surface, covering the operations
2326
+ * most useful for the matrix backend. The full module has 150+ exports
2327
+ * across algebra, arithmetic, signal, statistics, etc.
2328
+ */
2329
+ interface RustWasmExports {
2330
+ memory: WebAssembly.Memory;
2331
+ multiplyDense: (aPtr: number, aRows: number, aCols: number, bPtr: number, bRows: number, bCols: number, resultPtr: number) => void;
2332
+ multiplyDenseSIMD: (aPtr: number, aRows: number, aCols: number, bPtr: number, bRows: number, bCols: number, resultPtr: number) => void;
2333
+ multiplyVector: (aPtr: number, aRows: number, aCols: number, xPtr: number, resultPtr: number) => void;
2334
+ transpose: (dataPtr: number, rows: number, cols: number, resultPtr: number) => void;
2335
+ /** Thin SVD: writes U (m*k), S (k), V (n*k); k = min(m,n). */
2336
+ svd: (aPtr: number, m: number, n: number, uPtr: number, sPtr: number, vPtr: number, workPtr: number) => number;
2337
+ /** Singular values only: writes S (k); k = min(m,n). */
2338
+ singularValues: (aPtr: number, m: number, n: number, sPtr: number, workPtr: number) => number;
2339
+ /** Scratch length (in f64s) required by `svd`. */
2340
+ svdWorkSize: (m: number, n: number) => number;
2341
+ /** Scratch length (in f64s) required by `singularValues`. */
2342
+ singularValuesWorkSize: (m: number, n: number) => number;
2343
+ simdAddF64: (aPtr: number, bPtr: number, resultPtr: number, length: number) => void;
2344
+ simdSubF64: (aPtr: number, bPtr: number, resultPtr: number, length: number) => void;
2345
+ simdMulF64: (aPtr: number, bPtr: number, resultPtr: number, length: number) => void;
2346
+ simdScaleF64: (aPtr: number, scalar: number, resultPtr: number, length: number) => void;
2347
+ simdAbsF64: (aPtr: number, resultPtr: number, length: number) => void;
2348
+ simdDotF64: (aPtr: number, bPtr: number, length: number) => number;
2349
+ simdSumF64: (aPtr: number, length: number) => number;
2350
+ simdNormF64: (aPtr: number, length: number) => number;
2351
+ simdMatMulF64: (aPtr: number, bPtr: number, cPtr: number, m: number, k: number, n: number) => void;
2352
+ simdMinF64: (aPtr: number, length: number) => number;
2353
+ simdMaxF64: (aPtr: number, length: number) => number;
2354
+ simdMeanF64: (aPtr: number, length: number) => number;
2355
+ simdVarianceF64: (aPtr: number, length: number, ddof: number) => number;
2356
+ simdStdF64: (aPtr: number, length: number, ddof: number) => number;
2357
+ luDecomposition: (aPtr: number, n: number, permPtr: number) => number;
2358
+ qrDecomposition: (aPtr: number, m: number, n: number, qPtr: number) => void;
2359
+ choleskyDecomposition: (aPtr: number, n: number, lPtr: number) => number;
2360
+ eigsSymmetric: (matrixPtr: number, n: number, precision: number, eigenvaluesPtr: number, eigenvectorsPtr: number, workPtr: number) => number;
2361
+ laInv: (aPtr: number, n: number, resultPtr: number, workPtr: number) => number;
2362
+ laDet: (aPtr: number, n: number, workPtr: number) => number;
2363
+ laSolve: (aPtr: number, bPtr: number, n: number, resultPtr: number, workPtr: number) => number;
2364
+ fft: (dataPtr: number, n: number, inverse: number) => void;
2365
+ fft2d: (dataPtr: number, rows: number, cols: number, inverse: number) => void;
2366
+ convolve: (signalPtr: number, n: number, kernelPtr: number, m: number, resultPtr: number) => void;
2367
+ rfft: (dataPtr: number, n: number, resultPtr: number) => void;
2368
+ statsMean: (aPtr: number, n: number) => number;
2369
+ statsMedian: (aPtr: number, n: number) => number;
2370
+ statsVariance: (aPtr: number, n: number, ddof: number) => number;
2371
+ statsStd: (aPtr: number, n: number, ddof: number) => number;
2372
+ statsSum: (aPtr: number, n: number) => number;
2373
+ statsMin: (aPtr: number, n: number) => number;
2374
+ statsMax: (aPtr: number, n: number) => number;
2375
+ rust_mat_mul_2x2: (aPtr: number, bPtr: number, outPtr: number) => void;
2376
+ rust_fft_4: (inPtr: number, outPtr: number) => void;
2377
+ rust_gamma: (x: number, outPtr: number) => void;
2378
+ [key: string]: unknown;
2379
+ }
2380
+ /**
2381
+ * Loading metrics for performance monitoring
1952
2382
  */
1953
- interface GPUMatrixBackendConfig {
1954
- /** Minimum elements to use GPU (default: 65536 = 256x256) */
1955
- minElements?: number;
1956
- /** Use global GPU backend instance */
1957
- useGlobalBackend?: boolean;
1958
- /** GPU backend options */
1959
- gpuOptions?: GPUBackendOptions;
1960
- /** Fall back to JS on GPU errors */
1961
- fallbackOnError?: boolean;
2383
+ interface RustLoadingMetrics {
2384
+ loadMs: number;
2385
+ compileMs: number;
2386
+ instantiateMs: number;
2387
+ totalMs: number;
2388
+ binarySize: number;
1962
2389
  }
1963
2390
  /**
1964
- * GPU Matrix Backend
1965
- *
1966
- * Implements MatrixBackend interface using WebGPU compute shaders.
1967
- * Provides significant acceleration for large matrices.
1968
- *
1969
- * @example
1970
- * ```typescript
1971
- * const gpu = new GPUMatrixBackend();
1972
- * await gpu.initialize();
2391
+ * Loader for the Rust-compiled WASM module.
1973
2392
  *
1974
- * const result = gpu.multiply(matrixA, matrixB);
1975
- * ```
2393
+ * Singleton pattern with lazy loading. The WASM binary is loaded
2394
+ * on first use and cached for subsequent calls.
1976
2395
  */
1977
- declare class GPUMatrixBackend implements MatrixBackend {
1978
- readonly type: BackendType;
1979
- private config;
1980
- private backend;
1981
- private capabilities;
1982
- private initPromise;
1983
- private _available;
1984
- constructor(config?: GPUMatrixBackendConfig);
2396
+ declare class RustWasmLoader {
2397
+ private static instance;
2398
+ private wasmInstance;
2399
+ private wasmMemory;
2400
+ private allocator;
2401
+ private _isLoaded;
2402
+ private loading;
2403
+ private lastMetrics;
2404
+ private constructor();
2405
+ static getInstance(): RustWasmLoader;
2406
+ get isLoaded(): boolean;
1985
2407
  /**
1986
- * Check if GPU is available in the current environment
2408
+ * Load the Rust WASM module.
2409
+ * Returns true on success, false if the binary is not available.
2410
+ * Safe to call multiple times (idempotent).
1987
2411
  */
1988
- isAvailable(): boolean;
2412
+ load(wasmPath?: string): Promise<boolean>;
2413
+ private doLoad;
1989
2414
  /**
1990
- * Initialize the GPU backend
2415
+ * Resolve the WASM binary path.
2416
+ * Checks several locations relative to the project root.
1991
2417
  */
1992
- initialize(): Promise<void>;
1993
- private doInitialize;
2418
+ private findWasmPath;
2419
+ private getImports;
1994
2420
  /**
1995
- * Check if operation should use GPU
2421
+ * Get the typed exports from the WASM instance.
1996
2422
  */
1997
- private shouldUseGPU;
2423
+ getExports(): RustWasmExports | null;
1998
2424
  /**
1999
- * Execute GPU operation with fallback
2425
+ * Get WASM linear memory.
2000
2426
  */
2001
- private executeWithFallback;
2427
+ getMemory(): WebAssembly.Memory | null;
2002
2428
  /**
2003
- * Get GPU capabilities
2429
+ * Get loading metrics.
2004
2430
  */
2005
- getCapabilities(): GPUCapabilities | null;
2431
+ getLoadingMetrics(): RustLoadingMetrics | null;
2006
2432
  /**
2007
- * Get backend statistics
2433
+ * Write a Float64Array into WASM memory and return the pointer.
2008
2434
  */
2009
- getStats(): ReturnType<GPUBackend['getStats']> | null;
2010
- add(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2435
+ writeF64(data: Float64Array | number[]): number;
2011
2436
  /**
2012
- * Async add operation using GPU
2437
+ * Allocate an empty Float64Array in WASM memory (for output buffers).
2438
+ * Returns the pointer.
2013
2439
  */
2014
- addAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
2015
- subtract(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2016
- multiplyElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2017
- divideElementwise(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2018
- scale(a: DenseMatrix, scalar: number): DenseMatrix;
2440
+ allocF64(length: number): number;
2019
2441
  /**
2020
- * Async scale operation using GPU
2442
+ * Write an Int32Array into WASM memory and return the pointer.
2021
2443
  */
2022
- scaleAsync(a: DenseMatrix, scalar: number): Promise<DenseMatrix>;
2023
- abs(a: DenseMatrix): DenseMatrix;
2024
- negate(a: DenseMatrix): DenseMatrix;
2025
- multiply(a: DenseMatrix, b: DenseMatrix): DenseMatrix;
2444
+ writeI32(data: Int32Array | number[]): number;
2026
2445
  /**
2027
- * Async matrix multiplication using GPU
2446
+ * Allocate an empty Int32Array in WASM memory.
2028
2447
  */
2029
- multiplyAsync(a: DenseMatrix, b: DenseMatrix): Promise<DenseMatrix>;
2030
- transpose(a: DenseMatrix): DenseMatrix;
2448
+ allocI32(length: number): number;
2031
2449
  /**
2032
- * Async transpose using GPU
2450
+ * Read a Float64Array from WASM memory.
2451
+ * Note: the returned array is a *copy* (safe after memory reset).
2033
2452
  */
2034
- transposeAsync(a: DenseMatrix): Promise<DenseMatrix>;
2035
- sum(a: DenseMatrix): number;
2036
- sumAxis(a: DenseMatrix, axis: 0 | 1): DenseMatrix;
2037
- norm(a: DenseMatrix): number;
2038
- dot(a: DenseMatrix, b: DenseMatrix): number;
2453
+ readF64(ptr: number, length: number): Float64Array;
2039
2454
  /**
2040
- * Update configuration
2455
+ * Read an Int32Array from WASM memory.
2041
2456
  */
2042
- updateConfig(config: Partial<GPUMatrixBackendConfig>): void;
2457
+ readI32(ptr: number, length: number): Int32Array;
2043
2458
  /**
2044
- * Get current configuration
2459
+ * Reset the bump allocator. Call between independent operations
2460
+ * to reclaim temporary memory.
2045
2461
  */
2046
- getConfig(): Required<GPUMatrixBackendConfig>;
2462
+ resetAllocator(): void;
2047
2463
  /**
2048
- * Destroy the backend
2464
+ * Reset the loader (for testing).
2049
2465
  */
2050
- destroy(): void;
2466
+ reset(): void;
2467
+ /**
2468
+ * Reset the singleton (for testing).
2469
+ */
2470
+ static resetInstance(): void;
2051
2471
  }
2052
2472
  /**
2053
- * Global GPU matrix backend instance
2473
+ * Global Rust WASM loader instance
2054
2474
  */
2055
- declare const gpuMatrixBackend: GPUMatrixBackend;
2475
+ declare const rustWasmLoader: RustWasmLoader;
2056
2476
  /**
2057
- * Create a GPU matrix backend with custom configuration
2477
+ * Initialize the Rust WASM module (call once at startup).
2478
+ * Returns true if loaded successfully, false if not available.
2058
2479
  */
2059
- declare function createGPUMatrixBackend(config?: GPUMatrixBackendConfig): GPUMatrixBackend;
2480
+ declare function initRustWasm(wasmPath?: string): Promise<boolean>;
2481
+
2482
+ /**
2483
+ * MathTS Matrix Configuration
2484
+ *
2485
+ * Centralized configuration for matrix operations, backend selection,
2486
+ * and performance tuning.
2487
+ *
2488
+ * @packageDocumentation
2489
+ */
2490
+
2491
+ /**
2492
+ * Operation type hints for backend selection.
2493
+ *
2494
+ * Defined here rather than in `BackendManager.ts` so that `config.ts` (the
2495
+ * lower-level module) owns it — `BackendManager` already imports `config`, so
2496
+ * sourcing the type the other way round closed an import cycle.
2497
+ */
2498
+ type OperationType = 'add' | 'subtract' | 'multiply' | 'multiplyElementwise' | 'transpose' | 'scale' | 'decomposition' | 'solve' | 'fft' | 'eig' | 'svd';
2060
2499
 
2061
2500
  /**
2062
2501
  * Backend Manager
@@ -2068,10 +2507,6 @@ declare function createGPUMatrixBackend(config?: GPUMatrixBackendConfig): GPUMat
2068
2507
  * @packageDocumentation
2069
2508
  */
2070
2509
 
2071
- /**
2072
- * Operation type hints for backend selection
2073
- */
2074
- type OperationType = 'add' | 'subtract' | 'multiply' | 'multiplyElementwise' | 'transpose' | 'scale' | 'decomposition' | 'solve';
2075
2510
  /**
2076
2511
  * Extended backend hints with operation-specific thresholds
2077
2512
  */
@@ -2080,11 +2515,16 @@ interface ExtendedBackendHints extends BackendHints {
2080
2515
  operationThresholds?: Partial<Record<OperationType, {
2081
2516
  wasm?: number;
2082
2517
  gpu?: number;
2518
+ rustWasm?: number;
2083
2519
  }>>;
2084
2520
  /** Enable automatic SIMD detection for WASM */
2085
2521
  autoSIMD?: boolean;
2086
2522
  /** Fallback to JS on backend failure */
2087
2523
  fallbackOnError?: boolean;
2524
+ /** Minimum elements to use Rust WASM backend (default: 1000) */
2525
+ rustWasmThreshold?: number;
2526
+ /** Operations that always prefer Rust WASM regardless of size */
2527
+ rustWasmPreferredOps?: OperationType[];
2088
2528
  }
2089
2529
  /**
2090
2530
  * Default extended hints
@@ -2122,7 +2562,15 @@ declare class BackendManager {
2122
2562
  */
2123
2563
  getHints(): Required<ExtendedBackendHints>;
2124
2564
  /**
2125
- * Get the best backend for a given operation and matrix size
2565
+ * Get the best backend for a given operation and matrix size.
2566
+ *
2567
+ * Selection priority:
2568
+ * 1. Preferred backend (if explicitly set)
2569
+ * 2. Heavy operations (fft, eig, svd, decomposition) -> Rust WASM (if loaded)
2570
+ * 3. Elements > gpuThreshold -> GPU (if available)
2571
+ * 4. Elements > rustWasmThreshold -> Rust WASM (if loaded)
2572
+ * 5. Elements > wasmThreshold -> AS WASM (if loaded)
2573
+ * 6. JS fallback
2126
2574
  */
2127
2575
  selectBackend(elementCount: number, operation?: OperationType): MatrixBackend;
2128
2576
  /**
@@ -2350,7 +2798,7 @@ declare function singularValues(matrix: number[][] | Float64Array, options?: Omi
2350
2798
  /**
2351
2799
  * Compute the pseudoinverse (Moore-Penrose inverse) using SVD
2352
2800
  */
2353
- declare function pinv(matrix: number[][], options?: SVDOptions): number[][];
2801
+ declare function pinv$1(matrix: number[][], options?: SVDOptions): number[][];
2354
2802
  /**
2355
2803
  * Low-rank approximation using SVD
2356
2804
  * Keeps only the top r singular values
@@ -2425,32 +2873,380 @@ declare function spectralRadiusWasm(matrix: number[][], options?: {
2425
2873
  }): Promise<number>;
2426
2874
 
2427
2875
  /**
2428
- * WASM-accelerated Singular Value Decomposition
2876
+ * WASM-accelerated Singular Value Decomposition.
2429
2877
  *
2430
- * Provides SVD computation with optional WASM acceleration.
2431
- * The Rust WASM crate currently exposes eigenvalue operations but not
2432
- * a direct SVD implementation. For symmetric matrices, SVD can be
2433
- * derived from eigendecomposition (singular values = |eigenvalues|).
2878
+ * Routes through the Rust WASM crate's direct one-sided Jacobi SVD
2879
+ * (`svd` export) for any real `m x n` matrix, and falls back to the
2880
+ * synchronous JavaScript Golub-Reinsch {@link svd} when the WASM module is
2881
+ * unavailable.
2434
2882
  *
2435
- * Strategy:
2436
- * - Symmetric matrices: WASM eig -> derive SVD
2437
- * - General matrices: JS Golub-Reinsch bidiagonalization (svd.ts)
2883
+ * Unlike the synchronous {@link svd} (which returns the *full* `m x m` /
2884
+ * `n x n` factors), `svdWasm` always returns the **thin / economy** form —
2885
+ * `U` is `m x k`, `V` is `n x k`, `k = min(m, n)` — on both the WASM and the
2886
+ * fallback path, so callers get a stable result shape.
2438
2887
  *
2439
2888
  * @packageDocumentation
2440
2889
  */
2441
2890
 
2442
2891
  /**
2443
- * WASM-accelerated SVD.
2444
- *
2445
- * For symmetric matrices, uses WASM eigendecomposition to derive SVD.
2446
- * For general matrices, falls back to the JavaScript Golub-Reinsch algorithm.
2892
+ * WASM-accelerated thin SVD. Always safe to call — falls back to the
2893
+ * synchronous JS SVD when the Rust WASM module is not available.
2447
2894
  *
2448
- * @param matrix - Input matrix (m x n) as 2D array
2449
- * @param options - SVD computation options
2450
- * @returns SVD decomposition { U, S, V, rank }
2895
+ * @param matrix - Input matrix (m x n) as a row-major 2D array
2896
+ * @param options - SVD options; `rankTolerance` controls the rank estimate
2897
+ * @returns thin SVD `{ U (m x k), S (k), V (n x k), rank }`
2451
2898
  */
2452
2899
  declare function svdWasm(matrix: number[][], options?: SVDOptions): Promise<SVDResult>;
2453
2900
 
2901
+ /**
2902
+ * Moore-Penrose Pseudoinverse (DenseMatrix primitive)
2903
+ *
2904
+ * Computes the pseudoinverse A⁺ of a DenseMatrix A via full SVD with
2905
+ * rcond·max(S) singular-value thresholding.
2906
+ *
2907
+ * Algorithm:
2908
+ * 1. Full SVD: A = U · diag(S) · Vᵀ (A is m×n)
2909
+ * U: m×m orthogonal, V: n×n orthogonal, S: min(m,n) values (descending).
2910
+ * 2. Threshold: s_inv_i = 1/s_i if s_i > rcond·max(S), else 0.
2911
+ * 3. Build: A⁺ = V · diag(s_inv) · Uᵀ (shape: n×m).
2912
+ *
2913
+ * Satisfies all four Moore-Penrose identities within numerical precision:
2914
+ * A · A⁺ · A = A
2915
+ * A⁺ · A · A⁺ = A⁺
2916
+ * (A · A⁺)ᵀ = A · A⁺
2917
+ * (A⁺ · A)ᵀ = A⁺ · A
2918
+ */
2919
+
2920
+ interface PinvOptions {
2921
+ /**
2922
+ * Relative condition threshold for singular-value truncation.
2923
+ * A singular value s_i is treated as zero when s_i ≤ rcond · max(S).
2924
+ * Default: 1e-10.
2925
+ */
2926
+ rcond?: number;
2927
+ }
2928
+ /**
2929
+ * Compute the Moore-Penrose pseudoinverse of a DenseMatrix.
2930
+ *
2931
+ * @param A - Input matrix (m × n).
2932
+ * @param opts - Optional rcond threshold (default 1e-10).
2933
+ * @returns A⁺, the pseudoinverse of A (n × m).
2934
+ */
2935
+ declare function pinv(A: DenseMatrix, opts?: PinvOptions): DenseMatrix;
2936
+
2937
+ /**
2938
+ * QR Decomposition (DenseMatrix primitive)
2939
+ *
2940
+ * Classical Gram-Schmidt with re-orthogonalisation. Adequate for the
2941
+ * well-conditioned matrices that arise in the tensor wrappers + the
2942
+ * `randomTensor` orthogonal-distribution code path. For pathological
2943
+ * matrices the Householder QR implemented in `WASMBackend.qrDecompositionJS`
2944
+ * is preferable, but Gram-Schmidt suffices for the current call sites.
2945
+ *
2946
+ * Two modes:
2947
+ * - 'reduced' (thin QR): Q is (m × k), R is (k × n), k = min(m, n).
2948
+ * - 'full' : Q is (m × m), R is (m × n).
2949
+ *
2950
+ * In 'reduced' mode A = Q · R reconstructs A to within `1e-12`.
2951
+ * Q's columns are orthonormal (Qᵀ · Q = I_k); R is upper-triangular.
2952
+ */
2953
+
2954
+ interface QRResult {
2955
+ /** Orthonormal Q factor. Reduced: (m × k); full: (m × m). */
2956
+ Q: DenseMatrix;
2957
+ /** Upper-triangular R factor. Reduced: (k × n); full: (m × n). */
2958
+ R: DenseMatrix;
2959
+ }
2960
+ interface QROptions {
2961
+ /** 'reduced' (default, thin QR) or 'full'. */
2962
+ mode?: 'reduced' | 'full';
2963
+ }
2964
+ /**
2965
+ * Compute the QR decomposition of `A` such that `A = Q · R`.
2966
+ *
2967
+ * @param A - Input matrix (m × n, m ≥ 0, n ≥ 0).
2968
+ * @param opts - Optional mode selector (`'reduced'` thin QR or `'full'` square Q).
2969
+ */
2970
+ declare function qr(A: DenseMatrix, opts?: QROptions): QRResult;
2971
+
2972
+ /**
2973
+ * LU Decomposition (DenseMatrix primitive)
2974
+ *
2975
+ * Doolittle's algorithm with partial (row) pivoting. Factorises a square
2976
+ * matrix A into P · A = L · U where:
2977
+ * - L is unit lower-triangular (1s on the diagonal).
2978
+ * - U is upper-triangular.
2979
+ * - P is returned as a row-permutation array: P[i] is the original-row
2980
+ * index now at position i after pivoting.
2981
+ *
2982
+ * Usage:
2983
+ * const { L, U, P } = lu(A);
2984
+ * // P[i] gives the original row moved to position i, so P · A = L · U.
2985
+ */
2986
+
2987
+ interface LUResult {
2988
+ /** Unit lower-triangular factor L. */
2989
+ L: DenseMatrix;
2990
+ /** Upper-triangular factor U. */
2991
+ U: DenseMatrix;
2992
+ /** Row permutation array of length n. P[i] is the original-row index now at position i. */
2993
+ P: number[];
2994
+ }
2995
+ /**
2996
+ * Perform LU decomposition with partial pivoting on a square `DenseMatrix`.
2997
+ *
2998
+ * Implements Doolittle's algorithm in compact form: the working array stores
2999
+ * L below the diagonal (unit diagonal implicit) and U on and above it.
3000
+ *
3001
+ * @throws {Error} if `A` is not square.
3002
+ * @throws {Error} if `A` is singular (zero pivot encountered).
3003
+ */
3004
+ declare function lu(A: DenseMatrix): LUResult;
3005
+
3006
+ /**
3007
+ * Cholesky Decomposition (DenseMatrix primitive)
3008
+ *
3009
+ * Right-looking algorithm. Factorises a symmetric positive-definite (SPD)
3010
+ * matrix A into A = L · Lᵀ where L is lower-triangular.
3011
+ *
3012
+ * Usage:
3013
+ * const { L } = cholesky(A);
3014
+ * // A ≈ L · L^T (to floating-point precision)
3015
+ */
3016
+
3017
+ interface CholeskyResult {
3018
+ /** Lower-triangular Cholesky factor L such that A = L · Lᵀ. */
3019
+ L: DenseMatrix;
3020
+ }
3021
+ /**
3022
+ * Compute the Cholesky decomposition of the symmetric positive-definite
3023
+ * `DenseMatrix` A such that A = L · Lᵀ.
3024
+ *
3025
+ * @throws {Error} if `A` is not square.
3026
+ * @throws {Error} if `A` is not positive definite (non-positive diagonal pivot).
3027
+ */
3028
+ declare function cholesky(A: DenseMatrix): CholeskyResult;
3029
+
3030
+ /**
3031
+ * Matrix Exponential — Scaling-and-Squaring with Padé-13 Approximant
3032
+ *
3033
+ * Implements Algorithm 10.20 from:
3034
+ * Higham, N. J. (2005). "The scaling and squaring method for the matrix
3035
+ * exponential revisited." SIAM J. Matrix Anal. Appl., 26(4), 1179–1193.
3036
+ *
3037
+ * Algorithm:
3038
+ * 1. Compute s = max(0, ceil(log2(||A||_1 / θ_13))) where θ_13 ≈ 5.372.
3039
+ * 2. Scale: B = A / 2^s.
3040
+ * 3. Compute the [13/13] Padé approximant R(B) = (U + V)^{-1} * (-U + V).
3041
+ * 4. Square s times: expm(A) = R(B)^(2^s).
3042
+ *
3043
+ * Works for any real square DenseMatrix. For large ||A||, uses scaling to
3044
+ * stay within the Padé approximant's accuracy radius.
3045
+ */
3046
+
3047
+ interface ExpmOptions {
3048
+ /**
3049
+ * When true, return the result as a DenseMatrix.
3050
+ * When false (default), work directly on the internal number[][] and
3051
+ * return as DenseMatrix anyway — this option is reserved for future use.
3052
+ */
3053
+ _reserved?: never;
3054
+ }
3055
+ /**
3056
+ * Compute the matrix exponential of a square DenseMatrix.
3057
+ *
3058
+ * Uses the Padé-13 scaling-and-squaring algorithm (Higham 2005).
3059
+ * Accurate to near machine precision for general real matrices.
3060
+ *
3061
+ * @param A - Square DenseMatrix (n × n).
3062
+ * @returns expm(A) as a DenseMatrix (n × n).
3063
+ * @throws Error if A is not square.
3064
+ *
3065
+ * @example
3066
+ * // expm(0) = I
3067
+ * matrixExpm(DenseMatrix.zeros(3, 3)) // => identity 3×3
3068
+ *
3069
+ * @example
3070
+ * // expm(t*I) = e^t * I
3071
+ * const tI = DenseMatrix.fromArray([[2,0],[0,2]]);
3072
+ * matrixExpm(tI) // => [[e^2, 0], [0, e^2]]
3073
+ */
3074
+ declare function matrixExpm(A: DenseMatrix): DenseMatrix;
3075
+
3076
+ /**
3077
+ * Matrix Logarithm — Schur-Padé inverse scaling-and-squaring (Slices 5.9a + 6.1)
3078
+ *
3079
+ * Implements the Schur-Padé algorithm based on:
3080
+ * Higham (2008) "Functions of Matrices: Theory and Computation," Chapter 11
3081
+ * (Algorithm 11.10).
3082
+ *
3083
+ * Algorithm (general Schur-based path, Slice 6.1):
3084
+ * 1. Schur decompose: A = Q · T · Q^T.
3085
+ * 2. Repeatedly take matrix square roots of T (Björck recurrence on upper-
3086
+ * triangular matrices) until ||T^{1/2^k} - I||_1 < 0.25.
3087
+ * 3. Evaluate log(I + X) via 16-point Gauss-Legendre quadrature.
3088
+ * 4. Scale back by 2^k; rotate by Q: logm(A) = Q · (2^k · log(T^{1/2^k})) · Q^T.
3089
+ *
3090
+ * For the eig-based fallback (diagonalisable matrices with positive real
3091
+ * eigenvalues): logm(A) = V · diag(log(λ)) · V^{-1}.
3092
+ */
3093
+
3094
+ interface LogmOptions {
3095
+ /**
3096
+ * Tolerance for the "near-identity" test.
3097
+ * Default: 0.25 (||M - I||_1 < tol triggers Padé path).
3098
+ */
3099
+ nearIdentityTol?: number;
3100
+ }
3101
+ /**
3102
+ * Compute the principal matrix logarithm of a square DenseMatrix.
3103
+ *
3104
+ * Algorithm (Slice 5.9a — inverse scaling-and-squaring + Padé quadrature):
3105
+ * 1. Repeatedly take matrix square roots until ||M - I||_1 < nearIdentityTol.
3106
+ * 2. Evaluate log(I + X) = X * ∫₀¹ (I + tX)^{-1} dt via 7-pt Gauss-Legendre.
3107
+ * 3. Scale back: logm(A) = 2^k * log(A^{1/2^k}).
3108
+ *
3109
+ * Falls back to eigendecomposition if the square-root sequence diverges
3110
+ * (i.e., if the matrix has no non-positive eigenvalues and is diagonalisable).
3111
+ *
3112
+ * Limitations (deferred to Slice 5.9b):
3113
+ * - Matrices with non-positive real eigenvalues: principal log is undefined.
3114
+ * - Matrices with complex eigenvalues: throws.
3115
+ * - Non-diagonalisable (defective) matrices: eig-fallback also throws.
3116
+ * - Full Schur-based inverse-scaling-and-squaring for general non-normal
3117
+ * matrices.
3118
+ *
3119
+ * @param A - Square DenseMatrix with positive real eigenvalues.
3120
+ * @returns logm(A) as a DenseMatrix.
3121
+ * @throws Error for matrices with non-positive or complex eigenvalues.
3122
+ *
3123
+ * @example
3124
+ * // logm(I) = 0
3125
+ * matrixLogm(DenseMatrix.eye(3)) // => zero matrix
3126
+ *
3127
+ * @example
3128
+ * // Round-trip: expm(logm(A)) ≈ A
3129
+ * const A = DenseMatrix.fromArray([[4, 1], [0, 9]]);
3130
+ * const logA = matrixLogm(A);
3131
+ * // expm(logA) ≈ A (to machine precision for diagonalisable A)
3132
+ */
3133
+ declare function matrixLogm(A: DenseMatrix, opts?: LogmOptions): DenseMatrix;
3134
+
3135
+ /**
3136
+ * Matrix Square Root — Hybrid approach (Slices 5.9a + 6.1)
3137
+ *
3138
+ * Computes the principal square root of a square matrix.
3139
+ *
3140
+ * Algorithm selection:
3141
+ * 1. For symmetric positive semi-definite matrices: symmetric eigendecomposition
3142
+ * with Gram-Schmidt re-orthogonalisation (handles repeated eigenvalues).
3143
+ * 2. For general matrices: Björck-Hammarling Schur-based algorithm
3144
+ * (Higham 2008, Algorithm 6.3):
3145
+ * a. Schur decompose: A = Q · T · Q^T.
3146
+ * b. Compute upper-triangular U with U^2 = T via back-substitution.
3147
+ * c. Rotate back: sqrtm(A) = Q · U · Q^T.
3148
+ * Falls back to Newton iteration for diagonalisable matrices when the
3149
+ * Schur path is unsuitable (e.g. negative eigenvalues in 1×1 blocks).
3150
+ *
3151
+ * References:
3152
+ * - Higham (2008) "Functions of Matrices" §6 (Algorithm 6.3).
3153
+ * - Björck & Hammarling (1983) "A Schur method for the square root of a matrix."
3154
+ */
3155
+
3156
+ interface SqrtmOptions {
3157
+ /**
3158
+ * Force the symmetric-eigendecomposition path even for non-SPD matrices.
3159
+ * By default, symmetry is auto-detected.
3160
+ */
3161
+ assumeSymmetric?: boolean;
3162
+ }
3163
+ /**
3164
+ * Compute the principal square root of a square DenseMatrix.
3165
+ *
3166
+ * For symmetric positive semi-definite A:
3167
+ * Uses symmetric eigendecomposition with Gram-Schmidt re-orthogonalisation.
3168
+ *
3169
+ * For general diagonalisable A with non-negative eigenvalues:
3170
+ * Uses Newton iteration Y_{k+1} = (Y_k + A * Y_k^{-1}) / 2, falling back
3171
+ * to the eig-based formula if Newton fails to converge.
3172
+ *
3173
+ * Slice 5.9a limitations:
3174
+ * - Matrices with negative real eigenvalues: throws.
3175
+ * - Matrices with complex eigenvalues: throws.
3176
+ * - Non-diagonalisable (defective) matrices: Newton may fail + eig fallback
3177
+ * may also fail. Full Schur-based Björck-Hammarling deferred to Slice 5.9b.
3178
+ *
3179
+ * @param A - Square DenseMatrix (n × n).
3180
+ * @param opts - Optional flags.
3181
+ * @returns sqrtm(A), the principal square root.
3182
+ * @throws Error for matrices with negative or complex eigenvalues.
3183
+ *
3184
+ * @example
3185
+ * // sqrtm(I) = I
3186
+ * matrixSqrtm(DenseMatrix.eye(3)) // => identity 3×3
3187
+ *
3188
+ * @example
3189
+ * // sqrtm(4*I) = 2*I
3190
+ * const A = DenseMatrix.fromArray([[4,0],[0,4]]);
3191
+ * matrixSqrtm(A) // => [[2,0],[0,2]]
3192
+ *
3193
+ * @example
3194
+ * // Round-trip: sqrtm(A)^2 ≈ A
3195
+ * const S = DenseMatrix.fromArray([[4,2],[2,3]]);
3196
+ * const R = matrixSqrtm(S);
3197
+ * // R * R ≈ S (to machine precision for SPD matrices)
3198
+ */
3199
+ declare function matrixSqrtm(A: DenseMatrix, opts?: SqrtmOptions): DenseMatrix;
3200
+
3201
+ /**
3202
+ * Schur Decomposition — Francis QR with double shifts (Slice 6.1)
3203
+ *
3204
+ * Computes the real Schur decomposition A = Q · T · Q^T where:
3205
+ * - Q is orthogonal (Q^T · Q = I)
3206
+ * - T is quasi-upper-triangular (real Schur form): diagonal blocks are
3207
+ * 1×1 (real eigenvalue) or 2×2 (complex-conjugate eigenvalue pair)
3208
+ *
3209
+ * Algorithm: Householder reduction to upper Hessenberg form followed by
3210
+ * Francis double-shift implicit QR iteration (Golub & Van Loan §7.5).
3211
+ *
3212
+ * References:
3213
+ * Golub & Van Loan (2013) "Matrix Computations," 4th ed., §7.5.
3214
+ * Higham (2008) "Functions of Matrices: Theory and Computation," §1.
3215
+ */
3216
+
3217
+ interface SchurResult {
3218
+ /** Orthogonal factor Q (Q^T · Q = I, Q · Q^T = I). */
3219
+ Q: DenseMatrix;
3220
+ /** Quasi-upper-triangular Schur form T (real Schur form). */
3221
+ T: DenseMatrix;
3222
+ }
3223
+ interface SchurOptions {
3224
+ /** Maximum QR iterations (default: 1000). */
3225
+ maxIterations?: number;
3226
+ /** Deflation tolerance (default: 1e-12). */
3227
+ tolerance?: number;
3228
+ }
3229
+ /**
3230
+ * Compute the real Schur decomposition of a square matrix:
3231
+ * A = Q · T · Q^T
3232
+ *
3233
+ * T is quasi-upper-triangular (real Schur form): 1×1 diagonal blocks for
3234
+ * real eigenvalues and 2×2 blocks for complex-conjugate pairs. Q is
3235
+ * orthogonal.
3236
+ *
3237
+ * For matrices with all real eigenvalues, T is upper triangular with
3238
+ * eigenvalues on the diagonal. For matrices with complex-conjugate eigenvalue
3239
+ * pairs, the corresponding 2×2 diagonal block has the form
3240
+ * [[a, b], [-b, a]] (approximately)
3241
+ * and the complex pair is a ± bi.
3242
+ *
3243
+ * @param A - Square DenseMatrix (n × n, real entries).
3244
+ * @param opts - Optional algorithm parameters.
3245
+ * @returns { Q, T } satisfying Q · T · Q^T ≈ A.
3246
+ * @throws Error if A is not square.
3247
+ */
3248
+ declare function matrixSchur(A: DenseMatrix, opts?: SchurOptions): SchurResult;
3249
+
2454
3250
  /**
2455
3251
  * Typed Matrix Operations
2456
3252
  *
@@ -2834,4 +3630,4 @@ declare function initializeParallelMatrix(): Promise<void>;
2834
3630
  */
2835
3631
  declare function terminateParallelMatrix(): Promise<void>;
2836
3632
 
2837
- export { BUILTIN_SHADERS, type BackendHints, BackendManager, BackendRegistry, type BackendType, BatchExecutor, BufferPool, DEFAULT_BACKEND_HINTS, DEFAULT_EXTENDED_HINTS, DenseMatrix, type EigOptions, type EigResult, type ExtendedBackendHints, GPUBackend, type GPUBackendOptions, type GPUBackendStatus, type GPUCapabilities, GPUContext, type GPUContextOptions, GPUMatrixBackend, type GPUMatrixBackendConfig, JSBackend, Matrix, type MatrixBackend, type MatrixDimensions, type MatrixEntry, type MatrixIndex, type MatrixType, type OperationType, ParallelBackend, type ParallelBackendConfig, type SVDOptions, type SVDResult, ShaderManager, type SliceSpec, SparseMatrix, type SyncConfig, SyncManager, type SyncStrategy, WASMBackend, type WASMBackendConfig, type WasmFeatures, abs, add, backendManager, backendRegistry, clearFeatureCache, column, cond, createBackendManager, createGPUMatrixBackend, createParallelBackend, createSyncManager, createWASMBackend, destroyGlobalGPU, destroyGlobalGPUBackend, detectGPUCapabilities, detectWasmFeatures, diag, diagonal, divide, dotMultiply, eig, eigWasm, eigvals, eigvalsWasm, exp, getCachedFeatures, getGlobalGPUBackend, getGlobalGPUContext, getRecommendedWorkgroupSize, gpuMatrixBackend, hasWebGPU, identity, initializeGlobalGPUBackend, initializeParallelMatrix, isAtomicsAvailable, isDenseMatrix, isMatrix, isSharedMemoryAvailable, isSparseMatrix, isWasmAvailable, jsBackend, log, lowRankApprox, matrix, max, mean, min, multiply, norm, norm2, normFro, ones, parallelBackend, parallelDiag, parallelDotMultiply, parallelIdentity, parallelMatrix, parallelMatrixAbs, parallelMatrixAdd, parallelMatrixColumn, parallelMatrixCos, parallelMatrixDiagonal, parallelMatrixDistance, parallelMatrixDivide, parallelMatrixDot, parallelMatrixExp, parallelMatrixHistogram, parallelMatrixLog, parallelMatrixMatvec, parallelMatrixMax, parallelMatrixMean, parallelMatrixMin, parallelMatrixMultiply, parallelMatrixNorm, parallelMatrixOperations, parallelMatrixOuter, parallelMatrixRow, parallelMatrixSin, parallelMatrixSize, parallelMatrixSqrt, parallelMatrixSquare, parallelMatrixStd, parallelMatrixSubset, parallelMatrixSubtract, parallelMatrixSum, parallelMatrixTan, parallelMatrixTrace, parallelMatrixTranspose, parallelMatrixVariance, parallelOnes, parallelRandom, parallelUnaryMinus, parallelZeros, pinv, pow, powerIteration, random, row, singularValues, size, spectralRadiusWasm, sqrt, square, subset, subtract, sum, svd, svdWasm, terminateParallelMatrix, trace, transpose, typedMatrixOperations, unaryMinus, wasmBackend, zeros };
3633
+ export { BUILTIN_SHADERS, type BackendHints, BackendManager, BackendRegistry, type BackendType, BatchExecutor, BufferPool, type CholeskyResult, DEFAULT_BACKEND_HINTS, DEFAULT_EXTENDED_HINTS, DenseMatrix, type EigOptions, type EigResult, type ExpmOptions, type ExtendedBackendHints, GPUBackend, type GPUBackendOptions, type GPUBackendStatus, type GPUCapabilities, GPUContext, type GPUContextOptions, GPUMatrixBackend, type GPUMatrixBackendConfig, JSBackend, type LUResult, type LogmOptions, Matrix, type MatrixBackend, type MatrixDimensions, type MatrixEntry, type MatrixIndex, type MatrixType, type OperationType, ParallelBackend, type ParallelBackendConfig, type PinvOptions, type QROptions, type QRResult, type RustLoadingMetrics, RustWASMBackend, type RustWASMBackendConfig, type RustWasmExports, RustWasmLoader, type SVDOptions, type SVDResult, type SchurOptions, type SchurResult, ShaderManager, type SliceSpec, SparseMatrix, type SqrtmOptions, type SyncConfig, SyncManager, type SyncStrategy, WASMBackend, type WASMBackendConfig, type WasmFeatures, abs, add, backendManager, backendRegistry, cholesky, clearFeatureCache, column, cond, createBackendManager, createGPUMatrixBackend, createParallelBackend, createRustWASMBackend, createSyncManager, createWASMBackend, destroyGlobalGPU, destroyGlobalGPUBackend, detectGPUCapabilities, detectWasmFeatures, diag, diagonal, divide, dotMultiply, eig, eigWasm, eigvals, eigvalsWasm, exp, getCachedFeatures, getGlobalGPUBackend, getGlobalGPUContext, getRecommendedWorkgroupSize, gpuMatrixBackend, hasWebGPU, identity, initRustWasm, initializeGlobalGPUBackend, initializeParallelMatrix, isAtomicsAvailable, isDenseMatrix, isMatrix, isSharedMemoryAvailable, isSparseMatrix, isWasmAvailable, jsBackend, log, lowRankApprox, lu, matrix, matrixExpm, matrixLogm, pinv as matrixPinv, matrixSchur, matrixSqrtm, max, mean, min, multiply, norm, norm2, normFro, ones, parallelBackend, parallelDiag, parallelDotMultiply, parallelIdentity, parallelMatrix, parallelMatrixAbs, parallelMatrixAdd, parallelMatrixColumn, parallelMatrixCos, parallelMatrixDiagonal, parallelMatrixDistance, parallelMatrixDivide, parallelMatrixDot, parallelMatrixExp, parallelMatrixHistogram, parallelMatrixLog, parallelMatrixMatvec, parallelMatrixMax, parallelMatrixMean, parallelMatrixMin, parallelMatrixMultiply, parallelMatrixNorm, parallelMatrixOperations, parallelMatrixOuter, parallelMatrixRow, parallelMatrixSin, parallelMatrixSize, parallelMatrixSqrt, parallelMatrixSquare, parallelMatrixStd, parallelMatrixSubset, parallelMatrixSubtract, parallelMatrixSum, parallelMatrixTan, parallelMatrixTrace, parallelMatrixTranspose, parallelMatrixVariance, parallelOnes, parallelRandom, parallelUnaryMinus, parallelZeros, pinv$1 as pinv, pow, powerIteration, qr, random, row, rustWasmBackend, rustWasmLoader, singularValues, size, spectralRadiusWasm, sqrt, square, subset, subtract, sum, svd, svdWasm, terminateParallelMatrix, trace, transpose, typedMatrixOperations, unaryMinus, wasmBackend, zeros };