Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

ndarray index constructor.

License

NotificationsYou must be signed in to change notification settings

stdlib-js/ndarray-index

About stdlib...

We believe in a future in which the web is a preferred environment for numerical computation. To help realize this future, we've built stdlib. stdlib is a standard library, with an emphasis on numerical and scientific computation, written in JavaScript (and C) for execution in browsers and in Node.js.

The library is fully decomposable, being architected in such a way that you can swap out and mix and match APIs and functionality to cater to your exact preferences and use cases.

When you use stdlib, you can be absolutely certain that you are using the most thorough, rigorous, well-written, studied, documented, tested, measured, and high-quality code out there.

To join us in bringing numerical computing to the web, get started by checking us out onGitHub, and please considerfinancially supporting stdlib. We greatly appreciate your continued support!

ndindex

NPM versionBuild StatusCoverage Status

ndarray index constructor.

In JavaScript, only strings and symbols are valid property names. When providing values for property names which are not strings or symbols, the values are serialized to stringsprior to attempting to access property values. For example, the following

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');// Create an ndarray:varx=array(newInt32Array([1,2,3,4]));// Define a list of indices for elements we want to retrieve from `x`:vary=[0,2];// Attempt to retrieve the desired elements:varv=x[y];// => desired: <ndarray>[ 1, 3 ]// returns undefined

is equivalent to

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));vary=[0,2];varv=x[y.toString()];// returns undefined// ...which is equivalent to:v=x['0,2'];// returns undefined

Accordingly, in order to circumvent built-in property access behavior and support non-traditional access patterns, one can leverageProxy objects which allow one to intercept property access and to perform transformations before attempting to access elements in a target object.

To support the access pattern shown in the example above, one can leverage built-in string serialization behavior to reconstruct the original property value provided prior to serialization. Thendindex constructor described below provides one such mechanism.

Specifically, instantiatedndindex objects are assigned a unique identifier and stored in a local cache. When provided as property values tondindex consumers, instantiated objects serialize to a string containing their unique identifier.ndindex consumers can then parse the serialized string to obtain the unique identifier and subsequently recover the originalndarray from the local cache.

Installation

npm install @stdlib/ndarray-index

Alternatively,

  • To load the package in a website via ascript tag without installation and bundlers, use theES Module available on theesm branch (seeREADME).
  • If you are using Deno, visit thedeno branch (seeREADME for usage intructions).
  • For use in Observable, or in browser/node environments, use theUniversal Module Definition (UMD) build available on theumd branch (seeREADME).

Thebranches.md file summarizes the available branches and displays a diagram illustrating their relationships.

To view installation and usage instructions specific to each branch build, be sure to explicitly navigate to the respective README files on each branch, as linked to above.

Usage

varndindex=require('@stdlib/ndarray-index');

ndindex( x[, options] )

Wraps a providedndarray as an index object.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>

The constructor accepts the following arguments:

  • x: inputndarray.
  • options: function options.

The constructor accepts the following options:

  • kind: specifies whether a providedndarray is a specialized kind of integer inputndarray. This option is only applicable whenx is an integerndarray. Must be one of the following:

    • cartesian: anndarray containing Cartesian indices.
    • linear: anndarray containing indices representing locations in linear memory.

    Default:''.

  • persist: boolean indicating whether to continue persisting an index object after first usage. Default:false.

By default, anndindex is invalidated and removed from an internal cache immediately after a consumer resolves the underlying data associated with anndindex instance using thendindex.get() static method. Immediate invalidation and cache removal ensures that references to the underlyingndarray data are not the source of memory leaks.

One may, however, want to reuse anndindex instance to avoid additional memory allocation. In order to persist anndindex and prevent automatic cache invalidation, set thepersist option totrue.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x,{'persist':true});// returns <ndindex>// ...varo=ndindex.get(idx.id);// returns {...}// ...o=ndindex.get(idx.id);// returns {...}// ...// Explicitly free the index object:ndindex.free(idx.id);

In order toprevent memory leaks when working with persistedndindex instances, onemust remember to manually free persisted instances using thendindex.free() method.


Properties

ndindex.name

String value of thendindex constructor name.

varstr=ndindex.name;// returns 'ndindex'

ndindex.prototype.data

Read-only property returning anndarray view of the underlyingndarray data associated with anndindex instance.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>varv=idx.data;// returns <ndarray>

ndindex.prototype.dtype

Read-only property returning thedata type of the underlyingndarray associated with anndindex instance.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>vardt=idx.dtype;// returns 'int32'

ndindex.prototype.id

Read-only property returning the unique identifier associated with anndindex instance.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>varid=idx.id;// returns <string>

The identifier should be used byndindex consumers to resolve the underlying data associated with anndindex instance.

ndindex.prototype.isCached

Read-only property returning a boolean indicating whether anndindex instance is actively cached.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>varout=idx.isCached;// returns true

ndindex.prototype.kind

Read-only property returning thendarray index kind.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x,{'kind':'linear'});// returns <ndindex>varv=idx.kind;// returns 'linear'

The followingndarray index kinds are supported:

  • cartesian: an ndarray index object containing Cartesian indices.
  • linear: an ndarray index object for indices representing locations in linear memory.

ndindex.prototype.type

Read-only property returning thendarray index type.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>vart=idx.type;// returns 'int'

The followingndarray index types are supported:

  • mask: maskndarray, in which a value of zero indicates to include a respective element and a value of one indicates to exclude a respective element. A maskndarray is the complement of a booleanndarray.
  • bool: booleanndarray, in which a value oftrue indicates to include a respective element and a value offalse indicates to exclude a respective element. A booleanndarray is the complement of a maskndarray.
  • int: integerndarray, in which each element is an index indicating the position of an element to include. Elements arenot required to be unique (i.e., more than element may resolve to the same position).

Methods

ndindex.free( id )

Frees thendindex associated with a provided identifier.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x,{'persist':true});// returns <ndindex>// ...varout=ndindex.free(idx.id);// returns true

Once anndindex is freed, the instance is invalid and can no longer be used. Any subsequentndindex operations (i.e., property and method access) will raise an exception.

ndindex.get( id )

Returns thendarray associated with thendindex having a provided identifier.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x,{'persist':true});// returns <ndindex>// ...varo=ndindex.get(idx.id);// returns {...}vard=o.data;// returns <ndarray>vart=o.type;// returns 'int'vardt=o.dtype;// returns 'int32'

The returned object has the following properties:

  • data: the underlying "base"ndarray view associated with thendindex identified by the providedid.
  • type: the type ofndarray index. One of the following:'int','bool', or'mask'.
  • kind: thendarray index "kind". One of the following:'','cartesian', or'linear'.
  • dtype: the data type of the underlyingndarray.

If thendindex associated with a provided identifier was not explicitly persisted, calling this method will cause thendindex to be invalidated and removed from an internal cache. Any subsequent instance operations (i.e., property and method access) will raise an exception.

ndindex.cartesianIndex( x[, options] )

Wraps a providedndarray as a Cartesian index object.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]),{'shape':[2,2]});varidx=ndindex.cartesianIndex(x);// returns <ndindex>

This method is a convenience method for creating anndindex with thekind option set to'cartesian'. The function accepts the same arguments and options asndindex above.

ndindex.linearIndex( x[, options] )

Wraps a providedndarray as a linear index object.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=ndindex.linearIndex(x);// returns <ndindex>

This method is a convenience method for creating anndindex with thekind option set to'linear'. The function accepts the same arguments and options asndindex above.

ndindex.prototype.toString()

Serializes anndindex as a string.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>varstr=idx.toString();// e.g., 'ndindex<0>'

Anndindex is intended to be an opaque object used by objects supporting "fancy" indexing (e.g.,fancy ndarrays). As such, when serialized as a string, a serializedndindex includes only the unique identifier associated with the respective instance.

ndindex.prototype.toJSON()

Serializes anndindex as aJSON object.

vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);// returns <ndindex>varo=idx.toJSON();// returns { 'type': 'ndindex', 'kind': '', 'data': { ... }}

JSON.stringify() implicitly calls this method when stringifying anndindex instance.


Notes

  • ndindex instances have no explicit functionality; however, they are used by"fancy" ndarrays and other packages for element retrieval and assignment.

  • Becausendindex instances leverage an internal cache implementing thesingleton pattern, onemust be sure to use the samendindex constructor asndindex consumers. If one uses a differentndindex constructor, the consumer willnot be able to resolve anndarray view of the originalndarray, as the consumer will attempt to resolve anndindex instance in the wrong internal cache.

  • Because non-persistedndindex instances are freed after first use, in order to avoid holding onto memory and to allow garbage collection, one should avoid scenarios in which anndindex is never used. For example,

    vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);varo;if(x.get(0)===0){// Do something with `idx`...o=ndindex.get(idx.id);// ...}

    will leak memory asidx is only consumed within anif block which never evaluates. In such scenarios, one should either refactor to avoid inadvertently holding onto memory or explicitly free thendindex.

    vararray=require('@stdlib/ndarray-array');varInt32Array=require('@stdlib/array-int32');varx=array(newInt32Array([1,2,3,4]));varidx=newndindex(x);varo;if(x.get(0)===0){// Do something with `idx`...o=ndindex.get(idx.id);// ...}else{ndindex.free(idx.id);}

Examples

varempty=require('@stdlib/ndarray-empty');varndindex=require('@stdlib/ndarray-index');varx=empty([5],{'dtype':'uint8'});vari=newndindex(x);// returns <ndindex>varo=ndindex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);x=empty([5],{'dtype':'generic'});i=newndindex(x);// returns <ndindex>o=ndindex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);x=empty([5],{'dtype':'bool'});i=newndindex(x);// returns <ndindex>o=ndindex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);x=empty([5],{'dtype':'int32'});i=newndindex(x);// returns <ndindex>o=ndindex.get(i.id);// returns {...}console.log('Type: %s. Data type: %s.',o.type,o.dtype);

See Also


Notice

This package is part ofstdlib, a standard library for JavaScript and Node.js, with an emphasis on numerical and scientific computing. The library provides a collection of robust, high performance libraries for mathematics, statistics, streams, utilities, and more.

For more information on the project, filing bug reports and feature requests, and guidance on how to developstdlib, see the main projectrepository.

Community

Chat


License

SeeLICENSE.

Copyright

Copyright © 2016-2025. The StdlibAuthors.


[8]ページ先頭

©2009-2025 Movatter.jp