CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-cowasm--py-numpy

WebAssembly build of the NumPy Python library for JavaScript environments

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

@cowasm/py-numpy

A WebAssembly build of the NumPy Python library that provides the compiled NumPy distribution for use with python-wasm. This package serves as a dependency provider, supplying the path to WebAssembly-compiled NumPy files that enable NumPy functionality in JavaScript environments through the python-wasm interpreter.

Package Information

  • Package Name: @cowasm/py-numpy
  • Package Type: npm
  • Language: JavaScript (providing access to Python NumPy via WebAssembly)
  • Installation: npm install @cowasm/py-numpy
  • NumPy Version: 1.24.2
  • Python Compatibility: CPython 3.11.x

Core Imports

const { path } = require("@cowasm/py-numpy");

For ES modules:

import { path } from "@cowasm/py-numpy";

Basic Usage

Important: This package only provides a filesystem path to the compiled NumPy distribution. It does not expose NumPy functionality directly to JavaScript. All NumPy operations must be performed through the python-wasm interpreter, which loads and executes the WebAssembly-compiled NumPy library.

const { syncPython } = require("python-wasm");
const numpyPath = require("@cowasm/py-numpy").path;

// Initialize Python with access to NumPy
const python = await syncPython();

// Import and use NumPy in Python
python.exec("import numpy as np");

// Create arrays and perform operations
python.exec(`
arr = np.array([1, 2, 3, 4, 5])
result = np.sum(arr)
print(f"Sum: {result}")
`);

// Access results
const arrayRepr = python.repr("arr");
console.log("Array:", arrayRepr); // Array: array([1, 2, 3, 4, 5])

const sumResult = python.repr("result");
console.log("Sum:", sumResult); // Sum: 15

Architecture

The @cowasm/py-numpy package follows the CoWasm architecture:

  • WebAssembly Compilation: NumPy source code compiled to WebAssembly using Zig cross-compiler with LLVM backend
  • WASI Runtime: Executes under WebAssembly System Interface (WASI) for cross-platform compatibility
  • Dynamic Linking: Uses shared dynamic libraries pattern for efficient code sharing
  • Python Integration: Seamlessly integrates with python-wasm interpreter for Python-style API access
  • Patch System: Applies 6 compatibility patches to upstream NumPy for WebAssembly execution

Capabilities

WASM Distribution Path

This is the primary and only direct API provided by @cowasm/py-numpy. It supplies the filesystem path to the WebAssembly-compiled NumPy distribution.

/**
 * Path to the WebAssembly distribution directory containing NumPy WASM files
 * This is the only export from @cowasm/py-numpy - actual NumPy functionality
 * is accessed through python-wasm using this path
 */
const path: string;

The path points to the dist/wasm directory containing all compiled NumPy WebAssembly modules and supporting files. This path is used internally by python-wasm to locate and load the NumPy library.

NumPy API Access via python-wasm

Note: The following NumPy functionality is NOT directly provided by @cowasm/py-numpy, but rather accessed through the python-wasm interpreter which uses the path provided by this package. All NumPy functionality is accessed through Python code executed via the python-wasm interpreter. The complete NumPy 1.24.2 API is available, including:

Array Creation and Manipulation:

import numpy as np

# Array creation
arr = np.array([1, 2, 3, 4, 5])
zeros = np.zeros((3, 4))
ones = np.ones(10)
linspace = np.linspace(0, 10, 50)

# Array operations
reshaped = arr.reshape(5, 1)
concatenated = np.concatenate([arr, arr])

Mathematical Operations:

# Basic math
result = np.sum(arr)
mean_val = np.mean(arr)
std_dev = np.std(arr)

# Trigonometric functions
sine_vals = np.sin(arr)
cosine_vals = np.cos(arr)

# Linear algebra
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
dot_product = np.dot(matrix_a, matrix_b)

Statistical Functions:

# Statistical operations
maximum = np.max(arr)
minimum = np.min(arr)
median_val = np.median(arr)
percentile = np.percentile(arr, 75)

Array Indexing and Slicing:

# Indexing
first_element = arr[0]
last_element = arr[-1]
slice_result = arr[1:4]

# Boolean indexing
filtered = arr[arr > 2]

Integration with CoWasm Ecosystem

The package integrates with other CoWasm components:

  • @cowasm/cpython: Provides the WebAssembly Python interpreter
  • @cowasm/kernel: Supplies the WASM runtime kernel and POSIX compatibility layer
  • python-wasm: High-level interface for executing Python code with NumPy support

Platform Support

  • Node.js: Version 16+ with WebAssembly support
  • Browsers: Modern browsers supporting WebAssembly and appropriate threading models
  • Runtime Requirements: WASI-compatible WebAssembly runtime
  • Memory Model: Supports both SharedArrayBuffer and Service Worker execution modes

Installation and Dependencies

npm install @cowasm/py-numpy

The package requires python-wasm as a peer dependency for actual NumPy functionality:

npm install python-wasm @cowasm/py-numpy

Usage Examples

Data Analysis Example

const { syncPython } = require("python-wasm");

async function analyzeData() {
  const python = await syncPython();
  
  python.exec(`
import numpy as np

# Create sample data
data = np.random.normal(100, 15, 1000)

# Statistical analysis
mean = np.mean(data)
std = np.std(data)
median = np.median(data)

# Find outliers (more than 2 standard deviations from mean)
outliers = data[np.abs(data - mean) > 2 * std]

print(f"Mean: {mean:.2f}")
print(f"Standard Deviation: {std:.2f}")
print(f"Median: {median:.2f}")
print(f"Number of outliers: {len(outliers)}")
  `);
}

analyzeData();

Linear Algebra Example

const { syncPython } = require("python-wasm");

async function linearAlgebra() {
  const python = await syncPython();
  
  python.exec(`
import numpy as np

# Create matrices
A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])

# Matrix operations
sum_matrices = A + B
product = np.dot(A, B)
transpose = A.T

# Eigenvalues and eigenvectors
eigenvals, eigenvecs = np.linalg.eig(A)

print("Matrix A:")
print(A)
print("Matrix B:")
print(B)
print("A + B:")
print(sum_matrices)
print("A @ B:")
print(product)
  `);
}

linearAlgebra();

Build Information

  • Upstream NumPy: Version 1.24.2 from https://github.com/numpy/numpy
  • Compilation Target: wasm32-wasi
  • Compiler Toolchain: Zig with LLVM backend
  • BLAS/LAPACK: Disabled (NPY_BLAS_ORDER=, NPY_LAPACK_ORDER=, BLAS=None, LAPACK=None, ATLAS=None)
  • Applied Patches:
    • 01-ENH-Add-support-for-platforms-with-missing-fenv-flag.patch
    • 02-cxx_compiler.patch
    • 03-disable-complex.patch
    • 04-random-no-lm.patch
    • 05-no-backtrace.patch
    • 06-setup-setuptools.patch

Types

/**
 * The @cowasm/py-numpy package exports only a single property
 */
interface NumpyPackage {
  /** 
   * Path to WebAssembly distribution directory containing compiled NumPy files
   * This is the only export - NumPy functionality is accessed via python-wasm
   */
  path: string;
}

Error Handling

Errors in NumPy operations are handled by the Python interpreter and can be caught using standard Python exception handling within the python-wasm environment:

const python = await syncPython();

python.exec(`
import numpy as np

try:
    # This will raise a ValueError
    result = np.array([1, 2, 3]).reshape(2, 2)
except ValueError as e:
    print(f"NumPy error: {e}")
`);

Performance Considerations

  • WebAssembly Overhead: Approximately 2.5x slower than native CPython according to CoWasm benchmarks
  • Memory Usage: WebAssembly linear memory model with garbage collection through Python interpreter
  • Optimization: Compiled without advanced optimizations (cowasm-opt disabled) for better compatibility
  • Threading: Performance may vary between SharedArrayBuffer and Service Worker execution modes
Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@cowasm/py-numpy@1.1.x
Publish Source
CLI
Badge
tessl/npm-cowasm--py-numpy badge