- Notifications
You must be signed in to change notification settings - Fork56
📈 Multidimensional arrays for JavaScript
License
scijs/ndarray
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Modular multidimensional arrays for JavaScript.
Browse a number of ndarray-compatible modules in thescijs documentation
Coming from MATLAB or numpy? See:scijs/ndarray for MATLAB users
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:
varmat=ndarray(newFloat64Array([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 ofConway's game of life using ndarrays:
functionstepLife(next_state,cur_state){//Get array shapevarnx=cur_state.shape[0],ny=cur_state.shape[1]//Loop over all cellsfor(vari=1;i<nx-1;++i){for(varj=1;j<ny-1;++j){//Count neighborsvarn=0for(vardx=-1;dx<=1;++dx){for(vardy=-1;dy<=1;++dy){if(dx===0&&dy===0){continue}n+=cur_state.get(i+dx,j+dy)}}//Update state according to ruleif(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:
varx=ndarray(newFloat32Array(25),[5,5])vary=x.hi(4,4).lo(1,1)for(vari=0;i<y.shape[0];++i){for(varj=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 withbrowserify.
Install the library usingnpm:
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 usebrowserify. If you want live-reloading for faster debugging, check outbeefy.
Once you have ndarray installed, you can use it in your project as follows:
varndarray=require("ndarray")
The defaultmodule.exports method is the constructor for ndarrays. It creates an n-dimensional array view wrapping an underlying storage type
datais a 1D array storage. It is either an instance ofArray, a typed array, or an object that implementsget(), set(), .lengthshapeis the shape of the view (Default:data.length)strideis the resulting stride of the new array. (Default: row major)offsetis the offset to start the view (Default:0)
Returns an n-dimensional array view of the buffer
The central concept inndarray is the idea of a view. The way these work is very similar toSciPy'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 arrayarray.shape- The shape of the typed arrayarray.stride- The layout of the typed array in memoryarray.offset- The starting offset of the array in memory
Keeping a separate stride means that we can use the same data structure to support bothrow major and column major storage
To access elements of the array, you can use theset/get methods:
Retrieves elementi,j,... from the array. In psuedocode, this is implemented as follows:
functionget(i,j,...){returnthis.data[this.offset+this.stride[0]*i+this.stride[1]*j+ ...]}
Sets elementi,j,... tov. Again, in psuedocode this works like this:
functionset(i,j,...,v){returnthis.data[this.offset+this.stride[0]*i+this.stride[1]*j+ ...]=v}
Retrieves the index of the cell in the underlying ndarray. In JS,
functionindex(i,j, ...){returnthis.offset+this.stride[0]*i+this.stride[1]*j+ ...}
The following properties are created using Object.defineProperty and do not take up any physical memory. They can be useful in calculations involving ndarrays
Returns a string representing the undelying data type of the ndarray. Excluding generic data stores these types are compatible withtypedarray-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.
Returns the size of the array in logical elements.
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.
Returns the dimension of the array.
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 inconstant time (well, technicallyO(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:
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...).
This does the dual ofarray.lo(). Instead of shifting from the top-left, it truncates from the bottom-right of the array, returning a smaller array object. Usinghi andlo in combination lets you select ranges in the middle of an array.
Note:hi andlo do not commute. In general:
a.hi(3,3).lo(3,3)!=a.lo(3,3).hi(3,3)
Changes the stride length by rescaling. Negative indices flip axes. For example, here is how you create a reversed view of a 1D array:
varreversed=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:
varevens=a.step(2)varodds=a.lo(1).step(2)
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)
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:
varred=image.pick(null,null,0)vargreen=image.pick(null,null,1)varblue=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.
For more discussion about ndarrays, here are some talks, tutorials and articles about them:
- ndarray presentation
- Implementing multidimensional arrays in JavaScript
- Cache oblivious array operations
- Some experiments
(c) 2013-2016 Mikola Lysenko. MIT License
About
📈 Multidimensional arrays for JavaScript
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Uh oh!
There was an error while loading.Please reload this page.
Contributors4
Uh oh!
There was an error while loading.Please reload this page.

