Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
432 changes: 432 additions & 0 deletions MIGRATION_GUIDE.md

Large diffs are not rendered by default.

413 changes: 413 additions & 0 deletions REFACTORING_SUMMARY.md

Large diffs are not rendered by default.

591 changes: 591 additions & 0 deletions TYPESCRIPT_CONVERSION_SUMMARY.md

Large diffs are not rendered by default.

445 changes: 445 additions & 0 deletions TYPESCRIPT_WASM_ARCHITECTURE.md

Large diffs are not rendered by default.

34 changes: 34 additions & 0 deletions asconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"extends": "assemblyscript/std/assembly.json",
"targets": {
"release": {
"outFile": "lib/wasm/index.wasm",
"textFile": "lib/wasm/index.wat",
"sourceMap": true,
"optimizeLevel": 3,
"shrinkLevel": 2,
"converge": true,
"noAssert": true,
"runtime": "stub",
"importMemory": true,
"initialMemory": 256,
"maximumMemory": 16384,
"memoryBase": 0,
"exportRuntime": true
},
"debug": {
"outFile": "lib/wasm/index.debug.wasm",
"textFile": "lib/wasm/index.debug.wat",
"sourceMap": true,
"debug": true,
"runtime": "stub",
"importMemory": true,
"initialMemory": 256,
"maximumMemory": 16384
}
},
"options": {
"bindings": "esm",
"exportStart": "_start"
}
}
224 changes: 224 additions & 0 deletions examples/typescript-wasm-example.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
/**
* Example: Using TypeScript + WASM + Parallel Computing with mathjs
*
* This example demonstrates the new high-performance features:
* - WASM-accelerated matrix operations
* - Parallel/multicore computing
* - Automatic optimization selection
*/

import { MatrixWasmBridge } from '../src/wasm/MatrixWasmBridge.js'
import { ParallelMatrix } from '../src/parallel/ParallelMatrix.js'

async function main() {
console.log('=== TypeScript + WASM + Parallel Computing Example ===\n')

// Initialize WASM module
console.log('Initializing WASM...')
await MatrixWasmBridge.init()

// Check capabilities
const caps = MatrixWasmBridge.getCapabilities()
console.log('Capabilities:')
console.log(' WASM Available:', caps.wasmAvailable)
console.log(' Parallel Available:', caps.parallelAvailable)
console.log(' SIMD Available:', caps.simdAvailable)
console.log()

// Example 1: Matrix Multiplication Benchmark
console.log('=== Example 1: Matrix Multiplication Benchmark ===')
await matrixMultiplicationBenchmark()
console.log()

// Example 2: LU Decomposition
console.log('=== Example 2: LU Decomposition ===')
await luDecompositionExample()
console.log()

// Example 3: Parallel Matrix Operations
console.log('=== Example 3: Parallel Matrix Operations ===')
await parallelMatrixExample()
console.log()

// Example 4: Configuration Options
console.log('=== Example 4: Custom Configuration ===')
await customConfigurationExample()
console.log()

// Cleanup
console.log('Cleaning up...')
await MatrixWasmBridge.cleanup()
console.log('Done!')
}

/**
* Example 1: Matrix Multiplication Performance Comparison
*/
async function matrixMultiplicationBenchmark() {
const size = 500
console.log(`Matrix size: ${size}x${size}\n`)

// Generate random matrices
const a = new Float64Array(size * size)
const b = new Float64Array(size * size)
for (let i = 0; i < size * size; i++) {
a[i] = Math.random()
b[i] = Math.random()
}

// Benchmark with WASM (automatic selection)
console.log('Computing with automatic optimization...')
const start = performance.now()
const result = await MatrixWasmBridge.multiply(a, size, size, b, size, size)
const end = performance.now()

console.log(`Time: ${(end - start).toFixed(2)}ms`)
console.log(`Result dimensions: ${size}x${size}`)
console.log(`First 4 elements: [${result.slice(0, 4).join(', ')}]`)
}

/**
* Example 2: LU Decomposition
*/
async function luDecompositionExample() {
// Create a test matrix
const n = 4
const matrix = new Float64Array([
4, 3, 2, 1,
3, 4, 3, 2,
2, 3, 4, 3,
1, 2, 3, 4
])

console.log('Input matrix (4x4):')
printMatrix(matrix, n, n)
console.log()

// Perform LU decomposition
const { lu, perm, singular } = await MatrixWasmBridge.luDecomposition(matrix, n)

if (singular) {
console.log('Matrix is singular!')
} else {
console.log('LU Decomposition successful')
console.log('Permutation vector:', Array.from(perm))
console.log('\nL and U (combined):')
printMatrix(lu, n, n)
}
}

/**
* Example 3: Parallel Matrix Operations
*/
async function parallelMatrixExample() {
// Configure parallel execution
ParallelMatrix.configure({
minSizeForParallel: 100,
maxWorkers: 4,
useSharedMemory: true
})

const size = 1000
console.log(`Large matrix multiplication: ${size}x${size}`)
console.log('Using parallel/multicore execution\n')

// Generate large matrices
const a = new Float64Array(size * size)
const b = new Float64Array(size * size)
for (let i = 0; i < size * size; i++) {
a[i] = Math.random()
b[i] = Math.random()
}

// Multiply using parallel workers
console.log('Computing with parallel workers...')
const start = performance.now()
const result = await ParallelMatrix.multiply(a, size, size, b, size, size)
const end = performance.now()

console.log(`Time: ${(end - start).toFixed(2)}ms`)
console.log(`Workers used: 4 (or auto-detected)`)
console.log(`First 4 elements: [${result.slice(0, 4).join(', ')}]`)

// Test matrix addition
console.log('\nParallel matrix addition...')
const addStart = performance.now()
const sum = await ParallelMatrix.add(a, b, size * size)
const addEnd = performance.now()
console.log(`Time: ${(addEnd - addStart).toFixed(2)}ms`)
Copy link

Copilot AI Nov 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused variable sum.

Suggested change
console.log(`Time: ${(addEnd - addStart).toFixed(2)}ms`)
console.log(`Time: ${(addEnd - addStart).toFixed(2)}ms`)
console.log(`First 4 elements: [${sum.slice(0, 4).join(', ')}]`)

Copilot uses AI. Check for mistakes.

// Test matrix transpose
console.log('\nParallel matrix transpose...')
const transposeStart = performance.now()
const transposed = await ParallelMatrix.transpose(a, size, size)
const transposeEnd = performance.now()
console.log(`Time: ${(transposeEnd - transposeStart).toFixed(2)}ms`)
Copy link

Copilot AI Nov 19, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unused variable transposed.

Suggested change
console.log(`Time: ${(transposeEnd - transposeStart).toFixed(2)}ms`)
console.log(`Time: ${(transposeEnd - transposeStart).toFixed(2)}ms`)
console.log(`First 4 elements: [${transposed.slice(0, 4).join(', ')}]`)

Copilot uses AI. Check for mistakes.
}

/**
* Example 4: Custom Configuration
*/
async function customConfigurationExample() {
// Configure to use only JavaScript (no WASM)
console.log('Configuration 1: JavaScript only')
MatrixWasmBridge.configure({
useWasm: false,
useParallel: false
})

const size = 100
const a = new Float64Array(size * size).map(() => Math.random())
const b = new Float64Array(size * size).map(() => Math.random())

const start1 = performance.now()
await MatrixWasmBridge.multiply(a, size, size, b, size, size)
const end1 = performance.now()
console.log(`Time (JavaScript): ${(end1 - start1).toFixed(2)}ms\n`)

// Configure to use WASM only
console.log('Configuration 2: WASM only')
MatrixWasmBridge.configure({
useWasm: true,
useParallel: false,
minSizeForWasm: 0 // Always use WASM
})

const start2 = performance.now()
await MatrixWasmBridge.multiply(a, size, size, b, size, size)
const end2 = performance.now()
console.log(`Time (WASM): ${(end2 - start2).toFixed(2)}ms\n`)

// Configure for optimal performance
console.log('Configuration 3: Optimal (WASM + Parallel)')
MatrixWasmBridge.configure({
useWasm: true,
useParallel: true,
minSizeForWasm: 100,
minSizeForParallel: 1000
})

const largeSize = 500
const c = new Float64Array(largeSize * largeSize).map(() => Math.random())
const d = new Float64Array(largeSize * largeSize).map(() => Math.random())

const start3 = performance.now()
await MatrixWasmBridge.multiply(c, largeSize, largeSize, d, largeSize, largeSize)
const end3 = performance.now()
console.log(`Time (Optimal, ${largeSize}x${largeSize}): ${(end3 - start3).toFixed(2)}ms`)
}

/**
* Utility: Print matrix
*/
function printMatrix(data: Float64Array, rows: number, cols: number) {
for (let i = 0; i < rows; i++) {
const row = []
for (let j = 0; j < cols; j++) {
row.push(data[i * cols + j].toFixed(2))
}
console.log(' [' + row.join(', ') + ']')
}
}

// Run the examples
main().catch(console.error)
44 changes: 44 additions & 0 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { deleteAsync } from 'del'
import log from 'fancy-log'
import webpack from 'webpack'
import babel from 'gulp-babel'
import gulpTypescript from 'gulp-typescript'
import { mkdirp } from 'mkdirp'
import { cleanup, iteratePath } from './tools/docgenerator.js'
import { generateEntryFiles } from './tools/entryGenerator.js'
Expand All @@ -24,6 +25,8 @@ const COMPILE_DIR = path.join(__dirname, '/lib')
const COMPILE_BROWSER = `${COMPILE_DIR}/browser`
const COMPILE_CJS = `${COMPILE_DIR}/cjs`
const COMPILE_ESM = `${COMPILE_DIR}/esm` // es modules
const COMPILE_TS = `${COMPILE_DIR}/typescript`
const COMPILE_WASM = `${COMPILE_DIR}/wasm`
const COMPILE_ENTRY_LIB = `${COMPILE_CJS}/entry`

const FILE = 'math.js'
Expand Down Expand Up @@ -173,6 +176,34 @@ function compileEntryFiles () {
.pipe(gulp.dest(COMPILE_ENTRY_LIB))
}

function compileTypeScript () {
const tsProject = gulpTypescript.createProject('tsconfig.build.json')
return gulp.src('src/**/*.ts')
.pipe(tsProject())
.pipe(gulp.dest(COMPILE_TS))
}

function compileWasm (done) {
const { exec } = require('child_process')

// Create WASM output directory
mkdirp.sync(COMPILE_WASM)

// Compile WASM using AssemblyScript
exec('npm run build:wasm', (error, stdout, stderr) => {
if (error) {
log(`WASM compilation error: ${error.message}`)
done(error)
return
}
if (stderr) {
log(`WASM compilation stderr: ${stderr}`)
}
log('WASM compiled successfully')
done()
})
}

function writeCompiledHeader (cb) {
fs.writeFileSync(COMPILED_HEADER, createBanner())
cb()
Expand Down Expand Up @@ -270,7 +301,20 @@ gulp.task('default', gulp.series(
compileCommonJs,
compileEntryFiles,
compileESModules, // Must be after generateEntryFilesCallback
compileTypeScript,
compileWasm,
writeCompiledHeader,
bundle,
generateDocs
))

gulp.task('compile', gulp.series(
updateVersionFile,
generateEntryFilesCallback,
gulp.parallel(
compileCommonJs,
compileESModules,
compileTypeScript
),
compileEntryFiles
))
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -136,12 +136,16 @@
"lib": "./lib"
},
"scripts": {
"build": "gulp && npm run update-authors",
"build": "gulp && npm run build:wasm && npm run update-authors",
"build:wasm": "asc src-wasm/index.ts --config asconfig.json --target release",
"build:wasm:debug": "asc src-wasm/index.ts --config asconfig.json --target debug",
"build-and-test": "npm run build && npm run test:all && npm run lint",
"build:clean": "gulp clean",
"build:docs": "gulp docs",
"compile": "gulp compile",
"compile:ts": "tsc -p tsconfig.build.json",
"watch": "gulp watch",
"watch:ts": "tsc -p tsconfig.build.json --watch",
"lint": "eslint --cache --max-warnings 0 src/ test/ types/",
"format": "npm run lint -- --fix",
"validate:ascii": "gulp validate:ascii",
Expand Down
Loading
Loading