• Stars
    star
    1,165
  • Rank 40,073 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated almost 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

📈 Multidimensional arrays for JavaScript

ndarray

Modular multidimensional arrays for JavaScript.

browser support

build status

stable

Browse a number of ndarray-compatible modules in the scijs documentation
Coming from MATLAB or numpy? See: scijs/ndarray for MATLAB users
Big list of ndarray modules

Introduction

ndarrays provide higher dimensional views of 1D arrays. For example, here is how you can turn a length 4 typed array into an nd-array:

var mat = ndarray(new Float64Array([1, 0, 0, 1]), [2,2])

//Now:
//
// mat = 1 0
//       0 1
//

Once you have an nd-array you can access elements using .set and .get. For example, here is an implementation of Conway's game of life using ndarrays:

function stepLife(next_state, cur_state) {

  //Get array shape
  var nx = cur_state.shape[0], 
      ny = cur_state.shape[1]

  //Loop over all cells
  for(var i=1; i<nx-1; ++i) {
    for(var j=1; j<ny-1; ++j) {

      //Count neighbors
      var n = 0
      for(var dx=-1; dx<=1; ++dx) {
        for(var dy=-1; dy<=1; ++dy) {
          if(dx === 0 && dy === 0) {
            continue
          }
          n += cur_state.get(i+dx, j+dy)
        }
      }
      
      //Update state according to rule
      if(n === 3 || n === 3 + cur_state.get(i,j)) {
        next_state.set(i,j,1)
      } else {
        next_state.set(i,j,0)
      }
    }
  }
}

You can also pull out views of ndarrays without copying the underlying elements. Here is an example showing how to update part of a subarray:

var x = ndarray(new Float32Array(25), [5, 5])
var y = x.hi(4,4).lo(1,1)

for(var i=0; i<y.shape[0]; ++i) {
  for(var j=0; j<y.shape[1]; ++j) {
    y.set(i,j,1)
  }
}

//Now:
//    x = 0 0 0 0 0
//        0 1 1 1 0
//        0 1 1 1 0
//        0 1 1 1 0
//        0 0 0 0 0

ndarrays can be transposed, flipped, sheared and sliced in constant time per operation. They are useful for representing images, audio, volume graphics, matrices, strings and much more. They work both in node.js and with browserify.

Install

Install the library using npm:

npm install ndarray

You can also use ndarrays in a browser with any tool that follows the CommonJS/node module conventions. The most direct way to do this is to use browserify. If you want live-reloading for faster debugging, check out beefy.

API

Once you have ndarray installed, you can use it in your project as follows:

var ndarray = require("ndarray")

Constructor

ndarray(data[, shape, stride, offset])

The default module.exports method is the constructor for ndarrays. It creates an n-dimensional array view wrapping an underlying storage type

  • data is a 1D array storage. It is either an instance of Array, a typed array, or an object that implements get(), set(), .length
  • shape is the shape of the view (Default: data.length)
  • stride is the resulting stride of the new array. (Default: row major)
  • offset is the offset to start the view (Default: 0)

Returns an n-dimensional array view of the buffer

Members

The central concept in ndarray is the idea of a view. The way these work is very similar to SciPy's array slices. Views are affine projections to 1D storage types. To better understand what this means, let's first look at the properties of the view object. It has exactly 4 variables:

  • array.data - The underlying 1D storage for the multidimensional array
  • array.shape - The shape of the typed array
  • array.stride - The layout of the typed array in memory
  • array.offset - The starting offset of the array in memory

Keeping a separate stride means that we can use the same data structure to support both row major and column major storage

Element Access

To access elements of the array, you can use the set/get methods:

array.get(i,j,...)

Retrieves element i,j,... from the array. In psuedocode, this is implemented as follows:

function get(i,j,...) {
  return this.data[this.offset + this.stride[0] * i + this.stride[1] * j + ... ]
}

array.set(i,j,...,v)

Sets element i,j,... to v. Again, in psuedocode this works like this:

function set(i,j,...,v) {
  return this.data[this.offset + this.stride[0] * i + this.stride[1] * j + ... ] = v
}

array.index(i,j, ...)

Retrieves the index of the cell in the underlying ndarray. In JS,

function index(i,j, ...) {
  return this.offset + this.stride[0] * i + this.stride[1] * j + ...
}

Properties

The following properties are created using Object.defineProperty and do not take up any physical memory. They can be useful in calculations involving ndarrays

array.dtype

Returns a string representing the undelying data type of the ndarray. Excluding generic data stores these types are compatible with typedarray-pool. This is mapped according to the following rules:

Data type String
Int8Array "int8"
Int16Array "int16"
Int32Array "int32"
Uint8Array "uint8"
Uint16Array "uint16"
Uint32Array "uint32"
BigInt64Array "bigint64"
BigUint64Array "biguint64"
Float32Array "float32"
Float64Array "float64"
Array "array"
Uint8ArrayClamped "uint8_clamped"
Buffer "buffer"
Other "generic"

Generic arrays access elements of the underlying 1D store using get()/set() instead of array accessors.

array.size

Returns the size of the array in logical elements.

array.order

Returns the order of the stride of the array, sorted in ascending length. The first element is the first index of the shortest stride and the last is the index the longest stride.

array.dimension

Returns the dimension of the array.

Slicing

Given a view, we can change the indexing by shifting, truncating or permuting the strides. This lets us perform operations like array reversals or matrix transpose in constant time (well, technically O(shape.length), but since shape.length is typically less than 4, it might as well be). To make life simpler, the following interfaces are exposed:

array.lo(i,j,k,...)

This creates a shifted view of the array. Think of it as taking the upper left corner of the image and dragging it inward by an amount equal to (i,j,k...).

array.hi(i,j,k,...)

This does the dual of array.lo(). Instead of shifting from the top-left, it truncates from the bottom-right of the array, returning a smaller array object. Using hi and lo in combination lets you select ranges in the middle of an array.

Note: hi and lo do not commute. In general:

a.hi(3,3).lo(3,3)  !=  a.lo(3,3).hi(3,3)

array.step(i,j,k...)

Changes the stride length by rescaling. Negative indices flip axes. For example, here is how you create a reversed view of a 1D array:

var reversed = a.step(-1)

You can also change the step size to be greater than 1 if you like, letting you skip entries of a list. For example, here is how to split an array into even and odd components:

var evens = a.step(2)
var odds = a.lo(1).step(2)

array.transpose(p0, p1, ...)

Finally, for higher dimensional arrays you can transpose the indices without replicating the data. This has the effect of permuting the shape and stride values and placing the result in a new view of the same data. For example, in a 2D array you can calculate the matrix transpose by:

M.transpose(1, 0)

Or if you have a 3D volume image, you can shift the axes using more generic transformations:

volume.transpose(2, 0, 1)

array.pick(p0, p1, ...)

You can also pull out a subarray from an ndarray by fixing a particular axis. The way this works is you specify the direction you are picking by giving a list of values. For example, if you have an image stored as an nxmx3 array you can pull out the channel as follows:

var red   = image.pick(null, null, 0)
var green = image.pick(null, null, 1)
var blue  = image.pick(null, null, 2)

As the above example illustrates, passing a negative or non-numeric value to a coordinate in pick skips that index.

More information

For more discussion about ndarrays, here are some talks, tutorials and articles about them:

License

(c) 2013-2016 Mikola Lysenko. MIT License

More Repositories

1

get-pixels

Reads an image into an ndarray
JavaScript
540
star
2

fourier-transform

Minimalistic and efficient FFT implementation
JavaScript
167
star
3

cwise

Component-wise operations for ndarrays
JavaScript
118
star
4

save-pixels

Saves an ndarray as an image
JavaScript
89
star
5

ndarray-ops

ndarray operations
JavaScript
66
star
6

window-function

Collection of window functions
JavaScript
58
star
7

periodic-function

List of periodic functions normalized to 0..1 range
JavaScript
55
star
8

ndarray-fft

FFT for ndarrays
JavaScript
48
star
9

distance-transform

Distance transforms for ndarrays
JavaScript
36
star
10

almost-equal

Test if two floats are nearly equal
JavaScript
28
star
11

ndarray-resample

Downsample by a factor of two using sinc interpolation
JavaScript
26
star
12

newton-raphson-method

Find zeros of a function using the Newton-Raphson method
JavaScript
25
star
13

ode-rk4

Integrate a system of ODEs using the Fourth Order Runge-Kutta (RK-4) method
JavaScript
24
star
14

durand-kerner

Finds roots of polynomials by Weierstrauss' method
JavaScript
24
star
15

ode45-cash-karp

Integrate a system of Ordinary Differential Equations using the Fifth Order Adaptive Cash-Karp method
JavaScript
24
star
16

integrate-adaptive-simpson

Compute a definite integral using Simpson's Rule with adaptive quadrature
JavaScript
23
star
17

ndarray-show

display an ndarray
JavaScript
22
star
18

ndarray-fill

Fills an ndarray with a function
JavaScript
21
star
19

splines

Convenient and efficient B-splines.
JavaScript
20
star
20

nrrd-js

Handling of NRRD files in Javascript.
JavaScript
20
star
21

ndarray-linear-solve

solve a linear system with LU decomposition
JavaScript
19
star
22

nextafter

JS implementation of C stdlib nextafter
JavaScript
18
star
23

poly-roots

Find all roots of a polynomial using the Jenkins-Traub method
JavaScript
18
star
24

scijs-ndarray-for-matlab-users

Common scijs/ndarray operations for people familar with MATLAB (or at least not familiar with scijs)
18
star
25

ndarray-gemm

General matrix multiplication for ndarrays
JavaScript
18
star
26

ndarray-proxy

Turn functions into ndarrays
JavaScript
16
star
27

ndarray-linear-interpolate

Multilinear interpolation for ndarrays
JavaScript
16
star
28

cholesky-solve

[WIP] This module solves sparse symmetric positive definite linear systems by using the Cholesky decomposition
JavaScript
16
star
29

minimize-golden-section-1d

Minimize a function of a single variable using golden section search
JavaScript
14
star
30

ndarray-warp

Warps an ndarray
JavaScript
14
star
31

phase-align

Aligns a pair of ndarrays up to translation
JavaScript
14
star
32

zeros

Initialize an ndarray with zeros
JavaScript
13
star
33

ode-euler

Integrate a system of ODEs using the Euler method
JavaScript
13
star
34

gauss-random

Sample standard normal distribution
JavaScript
12
star
35

isndarray

Returns boolean whether the argument is a ndarray
JavaScript
11
star
36

ndarray-convolve

Convolutions and cross correlations for ndarrays
JavaScript
11
star
37

ndarray-blas-level1

BLAS Level 1 operations for ndarrays
JavaScript
11
star
38

ndarray-scratch

Pooled memory for ndarrays
JavaScript
11
star
39

ndarray-crout-decomposition

LU decomposition using the crout algorithm
JavaScript
11
star
40

contributing

Contribution guide lines
10
star
41

nifti-js

NIfTI support for Javascript
JavaScript
10
star
42

ndarray-sort

Sorts ndarrays in place
JavaScript
10
star
43

ndarray-pack

Packs an array-of-arrays into an ndarray
JavaScript
10
star
44

spiral-2d

Math for spirals
JavaScript
10
star
45

ndarray-imshow

Displays an ndarray as an image
JavaScript
10
star
46

ndarray-gaussian-filter

Gaussian blur for ndarrays
JavaScript
10
star
47

image-rotate

Rotates a 2D ndarray
JavaScript
10
star
48

ndarray-householder-qr

Householder triangularization for QR Factorization of ndarrays
JavaScript
10
star
49

ndarray-gram-schmidt-qr

Modified Gram-Schmidt Algorithm for QR Factorization of ndarrays
JavaScript
10
star
50

logo

logo for scijs
9
star
51

sphere-random

Sample a random point on a hypersphere
JavaScript
9
star
52

complex-deriv-fornberg

Compute the derivative of a complex analytic function using the method of Fornberg
JavaScript
9
star
53

tensor-decomposition

Higher order tensor decomposition
JavaScript
9
star
54

ndarray-bit

ndarrays of bits
JavaScript
9
star
55

baboon-image

The baboon test image
JavaScript
9
star
56

ndarray-blas-level2

BLAS Level 2 operations for ndarrays
JavaScript
9
star
57

ndarray-blas-level1-complex

BLAS Level 1 operations for complex ndarrays
JavaScript
9
star
58

pyramids

Various kinds of (image) pyramids for ndarrays of arbitrary dimension.
JavaScript
9
star
59

iota-array

Generates arrays of sequential integers
JavaScript
8
star
60

cwise-compiler

Just the compiler from cwise. No esprima dependencies
JavaScript
8
star
61

ndarray-select

Quick select algorithm for ndarrays
JavaScript
8
star
62

gauss-quadrature

Gauss-Legendre quadrature rules
JavaScript
8
star
63

ndarray-tests

Test numerical properties of ndarrays
JavaScript
8
star
64

complex-sqrt

Floating point complex square root
JavaScript
8
star
65

complex-division

Floating point complex division
JavaScript
8
star
66

poly-mult-fft

Multiplies polynomials together using an FFT
JavaScript
8
star
67

qr-solve

[WIP] This module solves sparse linear systems by using the QR-decomposition
JavaScript
8
star
68

finite-difference-stencil

Compute the coefficients of explicit or implicit finite difference schemes
JavaScript
8
star
69

gsl-const

physical constants for JS via GNU Scientific Library
JavaScript
8
star
70

cwise-parser

Parser for cwise
JavaScript
8
star
71

deriv

numerical derivatives of one-variable functions
JavaScript
7
star
72

ndarray-linspace

Fill an ndarray with equally spaced values
JavaScript
7
star
73

ndarray-distance

Lp distance between ndarrays
JavaScript
7
star
74

random-permutation

Generates a random permutation
JavaScript
7
star
75

ndarray-lup-factorization

LU factorization with pivoting for ndarrays
JavaScript
7
star
76

ndarray-translate-fft

Translate ndarrays with sinc interpolation
JavaScript
7
star
77

permutation-rank

Ranks and unranks permutations
JavaScript
7
star
78

ndarray-extract-contour

Generic contour/isosurface extraction code generator for ndarrays
JavaScript
7
star
79

ndarray-lup-solve

Solve ndarray Ax=b via LU factorization with pivoting
JavaScript
7
star
80

ndarray-blas-trsv

BLAS Level 2 TRSV (triangular solve) for ndarrays
JavaScript
7
star
81

ndarray-translate

Translate/shift ndarrays
JavaScript
7
star
82

ndarray-ldl-factorization

LDL Factorization for ndarrays
JavaScript
7
star
83

modified-newton-raphson

Find zeros a function using the Modified Newton-Raphson method
JavaScript
7
star
84

ndarray-determinant

Computes the determinant of an ndarray
JavaScript
7
star
85

richardson-extrapolation

Use Richardson Extrapolation sequence acceleration to compute the order of convergence and exact value of a sequence
JavaScript
7
star
86

ndarray-cholesky-factorization

Cholesky Factorization of ndarrays
JavaScript
6
star
87

dirichlet

Dirichlet/aliased sinc function
JavaScript
6
star
88

ndarray-moments

Statistical moments of ndarrays
JavaScript
6
star
89

integrate-simpson

Integrate a function of one variable using Simpson's Rule
JavaScript
6
star
90

quadratic-roots

Compute the real roots of a quadratic equation in a numerically stable manner
JavaScript
6
star
91

ndarray-vandermonde

Construct Vandermonde matrices with ndarrays
JavaScript
6
star
92

scijs.github.io

Web site for SciJS
6
star
93

ndarray-blas-gemv

BLAS Level 2 GEMV (Matrix-Vector multiply) for ndarrays
JavaScript
6
star
94

ndarray-function-basis

onstruct an ndarray basis given a sequence of points and functions
JavaScript
6
star
95

ndarray-band

Create a view of a band of an ndarray
JavaScript
5
star
96

ndarray-string

Creates an ndarray view of a string
JavaScript
5
star
97

ndarray-blas-trsv-complex

BLAS Level 2 TRSV (triangular solve) for complex ndarrays
JavaScript
5
star
98

ndarray-complex

Component-wise complex operations on ndarrays
JavaScript
5
star
99

companion-roots

Computes roots of polynomials by solving an eigenvalue problem
JavaScript
5
star
100

ndarray-normalize

Normalizes an ndarray to zero mean and unit variance
JavaScript
5
star