numrs2 0.3.1

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
/**
 * NumRS2 WebAssembly Demo Application
 *
 * This file demonstrates how to use NumRS2 in a web browser environment.
 * It provides examples of array operations, linear algebra, and statistics.
 */

// Import NumRS2 WASM module
// Note: The path will be './pkg/numrs2.js' after building with wasm-pack
import init, {
    get_version,
    is_simd_available,
    WasmArray
} from './pkg/numrs2.js';

let wasmInitialized = false;

/**
 * Initialize the WASM module
 */
async function initializeWasm() {
    try {
        await init();
        wasmInitialized = true;

        // Hide loading screen
        document.getElementById('loading').style.display = 'none';
        document.getElementById('main-content').style.display = 'block';

        // Display version and SIMD info
        try {
            const version = get_version();
            const simdAvailable = is_simd_available();

            document.getElementById('version-info').textContent = ` | Version: ${version}`;
            document.getElementById('simd-info').textContent = ` | SIMD: ${simdAvailable ? 'Enabled ⚡' : 'Disabled'}`;
        } catch (error) {
            console.error('Error getting version info:', error);
        }

        console.log('NumRS2 WASM module initialized successfully');
    } catch (error) {
        console.error('Failed to initialize WASM module:', error);
        document.getElementById('loading').innerHTML = `
            <div class="output error">
                Failed to load NumRS2 WASM module: ${error.message}
                <br><br>
                Please ensure you have built the WASM module using:
                <br>
                <code>wasm-pack build --target web --features wasm</code>
            </div>
        `;
    }
}

/**
 * Utility function to display output
 */
function displayOutput(elementId, content, isError = false) {
    const element = document.getElementById(elementId);
    if (!element) return;

    element.textContent = content;
    element.className = 'output';
    if (isError) {
        element.classList.add('error');
    } else {
        element.classList.add('success');
    }
}

/**
 * Utility function to check WASM initialization
 */
function checkWasmReady() {
    if (!wasmInitialized) {
        alert('WASM module is still loading. Please wait...');
        return false;
    }
    return true;
}

/**
 * Format array for display
 */
function formatArray(array, name = 'Array') {
    try {
        return `${name}:\n${array.toString()}`;
    } catch (error) {
        return `Error formatting array: ${error.message}`;
    }
}

/**
 * Measure execution time
 */
function measureTime(fn) {
    const start = performance.now();
    const result = fn();
    const end = performance.now();
    return { result, time: (end - start).toFixed(3) };
}

// ============================================================================
// Array Operations
// ============================================================================

/**
 * Create a zeros array
 */
window.createZerosArray = function() {
    if (!checkWasmReady()) return;

    try {
        const { result: arr, time } = measureTime(() =>
            WasmArray.zeros([3, 4])
        );

        displayOutput('array-output',
            `Created 3×4 zeros array in ${time}ms:\n\n${formatArray(arr)}`
        );
    } catch (error) {
        displayOutput('array-output',
            `Error creating zeros array: ${error.message}`,
            true
        );
    }
};

/**
 * Create a ones array
 */
window.createOnesArray = function() {
    if (!checkWasmReady()) return;

    try {
        const { result: arr, time } = measureTime(() =>
            WasmArray.ones([2, 5])
        );

        displayOutput('array-output',
            `Created 2×5 ones array in ${time}ms:\n\n${formatArray(arr)}`
        );
    } catch (error) {
        displayOutput('array-output',
            `Error creating ones array: ${error.message}`,
            true
        );
    }
};

/**
 * Create an arange array
 */
window.createArangeArray = function() {
    if (!checkWasmReady()) return;

    try {
        const { result: arr, time } = measureTime(() =>
            WasmArray.arange(0, 12, 1).reshape([3, 4])
        );

        displayOutput('array-output',
            `Created arange(0, 12) reshaped to 3×4 in ${time}ms:\n\n${formatArray(arr)}`
        );
    } catch (error) {
        displayOutput('array-output',
            `Error creating arange array: ${error.message}`,
            true
        );
    }
};

/**
 * Create a random array
 */
window.createRandomArray = function() {
    if (!checkWasmReady()) return;

    try {
        const { result: arr, time } = measureTime(() =>
            WasmArray.random([3, 3])
        );

        displayOutput('array-output',
            `Created 3×3 random array in ${time}ms:\n\n${formatArray(arr)}`
        );
    } catch (error) {
        displayOutput('array-output',
            `Error creating random array: ${error.message}`,
            true
        );
    }
};

/**
 * Array addition example
 */
window.arrayAddition = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.arange(0, 6, 1).reshape([2, 3]);
            const b = WasmArray.ones([2, 3]);
            return a.add(b);
        });

        displayOutput('arithmetic-output',
            `Array addition completed in ${time}ms:\n\n${formatArray(result, 'Result')}`
        );
    } catch (error) {
        displayOutput('arithmetic-output',
            `Error in array addition: ${error.message}`,
            true
        );
    }
};

/**
 * Array multiplication example
 */
window.arrayMultiplication = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.arange(1, 7, 1).reshape([2, 3]);
            const b = WasmArray.fill([2, 3], 2.0);
            return a.multiply(b);
        });

        displayOutput('arithmetic-output',
            `Element-wise multiplication completed in ${time}ms:\n\n${formatArray(result, 'Result')}`
        );
    } catch (error) {
        displayOutput('arithmetic-output',
            `Error in array multiplication: ${error.message}`,
            true
        );
    }
};

/**
 * Broadcasting example
 */
window.arrayBroadcasting = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.arange(0, 12, 1).reshape([4, 3]);
            return a.add_scalar(10.0);
        });

        displayOutput('arithmetic-output',
            `Broadcasting (add 10 to all elements) completed in ${time}ms:\n\n${formatArray(result, 'Result')}`
        );
    } catch (error) {
        displayOutput('arithmetic-output',
            `Error in broadcasting: ${error.message}`,
            true
        );
    }
};

// ============================================================================
// Linear Algebra Operations
// ============================================================================

/**
 * Matrix multiplication
 */
window.matrixMultiply = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.arange(0, 6, 1).reshape([2, 3]);
            const b = WasmArray.arange(0, 6, 1).reshape([3, 2]);
            return a.matmul(b);
        });

        displayOutput('linalg-output',
            `Matrix multiplication (2×3 @ 3×2) completed in ${time}ms:\n\n${formatArray(result, 'Result')}`
        );
    } catch (error) {
        displayOutput('linalg-output',
            `Error in matrix multiplication: ${error.message}`,
            true
        );
    }
};

/**
 * Matrix transpose
 */
window.matrixTranspose = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.arange(0, 12, 1).reshape([3, 4]);
            return a.transpose();
        });

        displayOutput('linalg-output',
            `Matrix transpose (3×4  4×3) completed in ${time}ms:\n\n${formatArray(result, 'Result')}`
        );
    } catch (error) {
        displayOutput('linalg-output',
            `Error in matrix transpose: ${error.message}`,
            true
        );
    }
};

/**
 * Matrix determinant
 */
window.matrixDeterminant = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.from_array([[1, 2], [3, 4]]);
            return a.det();
        });

        displayOutput('linalg-output',
            `Determinant of [[1,2],[3,4]] computed in ${time}ms:\n\ndet = ${result.toFixed(6)}`
        );
    } catch (error) {
        displayOutput('linalg-output',
            `Error computing determinant: ${error.message}`,
            true
        );
    }
};

/**
 * Matrix inverse
 */
window.matrixInverse = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const a = WasmArray.from_array([[4, 7], [2, 6]]);
            return a.inv();
        });

        displayOutput('linalg-output',
            `Matrix inverse of [[4,7],[2,6]] computed in ${time}ms:\n\n${formatArray(result, 'Inverse')}`
        );
    } catch (error) {
        displayOutput('linalg-output',
            `Error computing matrix inverse: ${error.message}`,
            true
        );
    }
};

// ============================================================================
// Statistics Operations
// ============================================================================

/**
 * Compute basic statistics
 */
window.computeStats = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const arr = WasmArray.arange(1, 101, 1);
            return {
                mean: arr.mean(),
                std: arr.std(),
                min: arr.min(),
                max: arr.max()
            };
        });

        displayOutput('stats-output',
            `Statistics for array [1, 2, ..., 100] computed in ${time}ms:\n\n` +
            `Mean: ${result.mean.toFixed(2)}\n` +
            `Std Dev: ${result.std.toFixed(2)}\n` +
            `Min: ${result.min.toFixed(2)}\n` +
            `Max: ${result.max.toFixed(2)}`
        );
    } catch (error) {
        displayOutput('stats-output',
            `Error computing statistics: ${error.message}`,
            true
        );
    }
};

/**
 * Compute correlation matrix
 */
window.computeCorrelation = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            const data = WasmArray.random([100, 3]);
            return data.corrcoef();
        });

        displayOutput('stats-output',
            `Correlation matrix for 100×3 random data computed in ${time}ms:\n\n${formatArray(result, 'Correlation')}`
        );
    } catch (error) {
        displayOutput('stats-output',
            `Error computing correlation: ${error.message}`,
            true
        );
    }
};

/**
 * Generate random distribution
 */
window.generateDistribution = function() {
    if (!checkWasmReady()) return;

    try {
        const { result, time } = measureTime(() => {
            return WasmArray.randn([1000]);
        });

        const stats = {
            mean: result.mean(),
            std: result.std()
        };

        displayOutput('stats-output',
            `Generated 1000 samples from normal distribution in ${time}ms:\n\n` +
            `Mean: ${stats.mean.toFixed(4)} (expected: 0.0)\n` +
            `Std Dev: ${stats.std.toFixed(4)} (expected: 1.0)\n\n` +
            `First 10 samples:\n${result.slice([0], [10]).toString()}`
        );
    } catch (error) {
        displayOutput('stats-output',
            `Error generating distribution: ${error.message}`,
            true
        );
    }
};

// ============================================================================
// Performance Benchmarks
// ============================================================================

/**
 * Benchmark array operations
 */
window.benchmarkArrayOps = function() {
    if (!checkWasmReady()) return;

    try {
        const size = 1000;
        const iterations = 100;

        // WASM benchmark
        const wasmTime = measureTime(() => {
            for (let i = 0; i < iterations; i++) {
                const a = WasmArray.random([size]);
                const b = WasmArray.random([size]);
                const c = a.add(b);
            }
        }).time;

        // JavaScript benchmark
        const jsTime = measureTime(() => {
            for (let i = 0; i < iterations; i++) {
                const a = Array.from({ length: size }, () => Math.random());
                const b = Array.from({ length: size }, () => Math.random());
                const c = a.map((val, idx) => val + b[idx]);
            }
        }).time;

        const speedup = (jsTime / wasmTime).toFixed(2);

        displayOutput('benchmark-output',
            `Array Addition Benchmark (${iterations} iterations, size ${size}):\n\n` +
            `NumRS2 WASM: ${wasmTime}ms\n` +
            `JavaScript: ${jsTime}ms\n\n` +
            `Speedup: ${speedup}x ${speedup > 1 ? '' : ''}`
        );
    } catch (error) {
        displayOutput('benchmark-output',
            `Error in benchmark: ${error.message}`,
            true
        );
    }
};

/**
 * Benchmark matrix operations
 */
window.benchmarkMatrixOps = function() {
    if (!checkWasmReady()) return;

    try {
        const size = 50;
        const iterations = 50;

        // WASM benchmark
        const wasmTime = measureTime(() => {
            for (let i = 0; i < iterations; i++) {
                const a = WasmArray.random([size, size]);
                const b = WasmArray.random([size, size]);
                const c = a.matmul(b);
            }
        }).time;

        // Note: JavaScript implementation would be very slow for matrix multiplication
        // We'll just show WASM performance

        displayOutput('benchmark-output',
            `Matrix Multiplication Benchmark (${iterations} iterations, ${size}×${size}):\n\n` +
            `NumRS2 WASM: ${wasmTime}ms\n` +
            `Average per operation: ${(wasmTime / iterations).toFixed(2)}ms\n\n` +
            `Note: Native JavaScript matrix multiplication would be significantly slower `
        );
    } catch (error) {
        displayOutput('benchmark-output',
            `Error in benchmark: ${error.message}`,
            true
        );
    }
};

// Initialize WASM when page loads
initializeWasm();