diff --git a/CHANGELOG.md b/CHANGELOG.md index c96e6fdc..cdc90b61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@
-## Unreleased (2024-08-16) +## Unreleased (2024-08-17)
@@ -20,6 +20,7 @@ ##### Features +- [`ba0c5d0`](https://github.com/stdlib-js/stdlib/commit/ba0c5d0a00c8f2b5eff6321b14dd62398be26be8) - add `ndarraylike2ndarray` to namespace - [`de17de3`](https://github.com/stdlib-js/stdlib/commit/de17de32867461079aae166d5cecbecb1da7f922) - update namespace TypeScript declarations [(#2593)](https://github.com/stdlib-js/stdlib/pull/2593) - [`b8bd516`](https://github.com/stdlib-js/stdlib/commit/b8bd51687cabdda74299cb37b9a5527fddd35aaa) - update namespace TypeScript declarations [(#2351)](https://github.com/stdlib-js/stdlib/pull/2351) - [`0adcae5`](https://github.com/stdlib-js/stdlib/commit/0adcae51386086e2ef5fb5d78402389cff776deb) - update namespace TypeScript declarations [(#1340)](https://github.com/stdlib-js/stdlib/pull/1340) @@ -809,6 +810,28 @@ This release closes the following issue: +
+ +#### [@stdlib/ndarray/ndarraylike2ndarray](https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ndarraylike2ndarray) + +
+ +
+ +##### Features + +- [`e7b56b1`](https://github.com/stdlib-js/stdlib/commit/e7b56b133fffc0bf83638ab267242c25eb8a359a) - add `ndarray/ndarraylike2ndarray` + +
+ + + +
+ +
+ + +
#### [@stdlib/ndarray/next-dtype](https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/next-dtype) @@ -1012,6 +1035,9 @@ A total of 4 people contributed to this release. Thank you to the following cont
+- [`ba0c5d0`](https://github.com/stdlib-js/stdlib/commit/ba0c5d0a00c8f2b5eff6321b14dd62398be26be8) - **feat:** add `ndarraylike2ndarray` to namespace _(by Athan Reines)_ +- [`e7b56b1`](https://github.com/stdlib-js/stdlib/commit/e7b56b133fffc0bf83638ab267242c25eb8a359a) - **feat:** add `ndarray/ndarraylike2ndarray` _(by Athan Reines)_ +- [`453c7f9`](https://github.com/stdlib-js/stdlib/commit/453c7f9f7c8ac5b8817b1d81f98af42570f1d0a5) - **refactor:** allow array-like objects containing submodes _(by Athan Reines)_ - [`dd48932`](https://github.com/stdlib-js/stdlib/commit/dd489326b8dcee32f41f2ef7c2bafcaa4eb6ce46) - **docs:** fix descriptions _(by Athan Reines)_ - [`54262c8`](https://github.com/stdlib-js/stdlib/commit/54262c89e70eae566591c6e87ece69b68ca09488) - **feat:** add `ndarraylike2ndarray` to namespace _(by Athan Reines)_ - [`5d01561`](https://github.com/stdlib-js/stdlib/commit/5d015616e9731e40d20f7d4dca6b136ae47cc9bc) - **feat:** add `ndarray/base/ndarraylike2ndarray` _(by Athan Reines)_ diff --git a/ctor/docs/types/index.d.ts b/ctor/docs/types/index.d.ts index e497a3f9..33180457 100644 --- a/ctor/docs/types/index.d.ts +++ b/ctor/docs/types/index.d.ts @@ -20,7 +20,7 @@ /// -import { Collection } from '@stdlib/types/array'; +import { Collection, ArrayLike } from '@stdlib/types/array'; import { ndarray, DataType, Mode, Order, Shape, Strides } from '@stdlib/types/ndarray'; import { Buffer } from 'buffer'; @@ -36,7 +36,7 @@ interface Options { /** * Specifies how to handle subscripts which exceed array dimensions on a per dimension basis (default: ['throw']). */ - submode?: Array; + submode?: ArrayLike; /** * Boolean indicating whether an array should be read-only (default: false). diff --git a/ctor/lib/validate.js b/ctor/lib/validate.js index 3240e107..57cff834 100644 --- a/ctor/lib/validate.js +++ b/ctor/lib/validate.js @@ -22,7 +22,7 @@ var isObject = require( '@stdlib/assert/is-plain-object' ); var hasOwnProp = require( '@stdlib/assert/has-own-property' ); -var isArray = require( '@stdlib/assert/is-array' ); +var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' ); var isIndexMode = require( './../../base/assert/is-index-mode' ); var isBoolean = require( '@stdlib/assert/is-boolean' ).isPrimitive; var format = require( '@stdlib/string/format' ); @@ -37,7 +37,7 @@ var format = require( '@stdlib/string/format' ); * @param {Object} opts - destination object * @param {Options} options - function options * @param {string} [options.mode] - specifies how to handle indices which exceed array dimensions -* @param {string} [options.submode] - specifies how to handle subscripts which exceed array dimensions +* @param {StringArray} [options.submode] - specifies how to handle subscripts which exceed array dimensions * @param {boolean} [options.readonly] - boolean indicating whether an array should be read-only * @returns {(Error|null)} null or an error object * @@ -65,7 +65,7 @@ function validate( opts, options ) { } if ( hasOwnProp( options, 'submode' ) ) { opts.submode = options.submode; - if ( !isArray( opts.submode ) ) { + if ( !isArrayLikeObject( opts.submode ) ) { return new TypeError( format( 'invalid option. `%s` option must be an array containing recognized modes. Option: `%s`.', 'submode', opts.submode ) ); } if ( opts.submode.length === 0 ) { diff --git a/lib/index.js b/lib/index.js index 0c9d119d..1a2fea07 100644 --- a/lib/index.js +++ b/lib/index.js @@ -261,6 +261,15 @@ setReadOnly( ns, 'minDataType', require( './../min-dtype' ) ); */ setReadOnly( ns, 'mostlySafeCasts', require( './../mostly-safe-casts' ) ); +/** +* @name ndarraylike2ndarray +* @memberof ns +* @readonly +* @type {Function} +* @see {@link module:@stdlib/ndarray/ndarraylike2ndarray} +*/ +setReadOnly( ns, 'ndarraylike2ndarray', require( './../ndarraylike2ndarray' ) ); + /** * @name ndims * @memberof ns diff --git a/ndarraylike2ndarray/README.md b/ndarraylike2ndarray/README.md new file mode 100644 index 00000000..c4198f6c --- /dev/null +++ b/ndarraylike2ndarray/README.md @@ -0,0 +1,130 @@ + + +# ndarraylike2ndarray + +> Convert an ndarray-like object to an [`ndarray`][@stdlib/ndarray/ctor]. + + + +
+ +
+ + + + + +
+ +## Usage + +```javascript +var ndarraylike2ndarray = require( '@stdlib/ndarray/ndarraylike2ndarray' ); +``` + +#### ndarraylike2ndarray( x\[, options] ) + +Converts an ndarray-like object to an [`ndarray`][@stdlib/ndarray/ctor]. + +```javascript +var array = require( '@stdlib/ndarray/array' ); + +var arr = array( [ [ 1, 2 ], [ 3, 4 ] ] ); +var out = ndarraylike2ndarray( arr ); +// returns +``` + +The function supports the same `options` as [`ndarray`][@stdlib/ndarray/ctor]. + +
+ + + + + +
+ +## Notes + +- If provided a **read-only** [`ndarray`][@stdlib/ndarray/ctor], the function returns a **read-only** [`ndarray`][@stdlib/ndarray/ctor]. + +
+ + + + + +
+ +## Examples + + + +```javascript +var array = require( '@stdlib/ndarray/array' ); +var ndarraylike2ndarray = require( '@stdlib/ndarray/ndarraylike2ndarray' ); + +// Create an ndarray: +var x = array( [ [ 1, 2 ], [ 3, 4 ] ] ); + +// Create another ndarray sharing the same data: +var out = ndarraylike2ndarray( x ); +// returns + +// Print various properties: +console.log( 'dtype: %s', out.dtype ); +console.log( 'ndims: %d', out.shape.length ); +console.log( 'length: %d', out.length ); +console.log( 'shape: [ %s ]', out.shape.join( ', ' ) ); +console.log( 'strides: [ %s ]', out.strides.join( ', ' ) ); +console.log( 'offset: %d', out.offset ); +console.log( 'order: %s', out.order ); +``` + +
+ + + + + +
+ +
+ + + + + + + + + + + + + + diff --git a/ndarraylike2ndarray/benchmark/benchmark.js b/ndarraylike2ndarray/benchmark/benchmark.js new file mode 100644 index 00000000..42ff9ff8 --- /dev/null +++ b/ndarraylike2ndarray/benchmark/benchmark.js @@ -0,0 +1,161 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var bench = require( '@stdlib/bench' ); +var Float64Array = require( '@stdlib/array/float64' ); +var ndarrayBase = require( './../../base/ctor' ); +var ndarray = require( './../../ctor' ); +var isCollection = require( '@stdlib/assert/is-collection' ); +var pkg = require( './../package.json' ).name; +var ndarraylike2ndarray = require( './../lib' ); + + +// MAIN // + +bench( pkg+'::base_ndarray', function benchmark( b ) { + var strides; + var values; + var buffer; + var offset; + var dtype; + var shape; + var order; + var out; + var i; + + dtype = 'float64'; + buffer = new Float64Array( 4 ); + shape = [ 2, 2 ]; + strides = [ 2, 1 ]; + offset = 0; + order = 'row-major'; + + values = [ + ndarrayBase( dtype, buffer, shape, strides, offset, order ), + ndarrayBase( dtype, buffer, shape, strides, offset, order ), + ndarrayBase( dtype, buffer, shape, strides, offset, order ), + ndarrayBase( dtype, buffer, shape, strides, offset, order ), + ndarrayBase( dtype, buffer, shape, strides, offset, order ) + ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = ndarraylike2ndarray( values[ i%values.length ] ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isCollection( out.data ) ) { + b.fail( 'should return a collection' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::ndarray', function benchmark( b ) { + var strides; + var values; + var buffer; + var offset; + var dtype; + var shape; + var order; + var out; + var i; + + dtype = 'float64'; + buffer = new Float64Array( 4 ); + shape = [ 2, 2 ]; + strides = [ 2, 1 ]; + offset = 0; + order = 'row-major'; + + values = [ + ndarray( dtype, buffer, shape, strides, offset, order ), + ndarray( dtype, buffer, shape, strides, offset, order ), + ndarray( dtype, buffer, shape, strides, offset, order ), + ndarray( dtype, buffer, shape, strides, offset, order ), + ndarray( dtype, buffer, shape, strides, offset, order ) + ]; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = ndarraylike2ndarray( values[ i%values.length ] ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isCollection( out.data ) ) { + b.fail( 'should return a collection' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); + +bench( pkg+'::ndarray_like', function benchmark( b ) { + var strides; + var values; + var buffer; + var offset; + var dtype; + var shape; + var order; + var out; + var obj; + var i; + + dtype = 'float64'; + buffer = new Float64Array( 4 ); + shape = [ 2, 2 ]; + strides = [ 2, 1 ]; + offset = 0; + order = 'row-major'; + + values = []; + for ( i = 0; i < 5; i++ ) { + obj = { + 'dtype': dtype, + 'data': buffer, + 'shape': shape, + 'strides': strides, + 'offset': offset, + 'order': order + }; + values.push( obj ); + } + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + out = ndarraylike2ndarray( values[ i%values.length ] ); + if ( typeof out !== 'object' ) { + b.fail( 'should return an object' ); + } + } + b.toc(); + if ( !isCollection( out.data ) ) { + b.fail( 'should return a collection' ); + } + b.pass( 'benchmark finished' ); + b.end(); +}); diff --git a/ndarraylike2ndarray/docs/repl.txt b/ndarraylike2ndarray/docs/repl.txt new file mode 100644 index 00000000..6f05981a --- /dev/null +++ b/ndarraylike2ndarray/docs/repl.txt @@ -0,0 +1,54 @@ + +{{alias}}( x[, options] ) + Converts an ndarray-like object to an ndarray. + + If provided a read-only ndarray, the function returns a read-only ndarray. + + Parameters + ---------- + x: ndarrayLike + Input ndarray-like object. + + options: Object (optional) + Options. + + options.mode: string (optional) + Specifies how to handle indices which exceed array dimensions. If equal + to 'throw', an ndarray instance throws an error when an index exceeds + array dimensions. If equal to 'normalize', an ndarray instance + normalizes negative indices and throws an error when an index exceeds + array dimensions. If equal to 'wrap', an ndarray instance wraps around + indices exceeding array dimensions using modulo arithmetic. If equal to + 'clamp', an ndarray instance sets an index exceeding array dimensions + to either `0` (minimum index) or the maximum index. Default: 'throw'. + + options.submode: Array (optional) + Specifies how to handle subscripts which exceed array dimensions. If a + mode for a corresponding dimension is equal to 'throw', an ndarray + instance throws an error when a subscript exceeds array dimensions. If + equal to 'normalize', an ndarray instance normalizes negative + subscripts and throws an error when a subscript exceeds array + dimensions. If equal to 'wrap', an ndarray instance wraps around + subscripts exceeding array dimensions using modulo arithmetic. If equal + to 'clamp', an ndarray instance sets a subscript exceeding array + dimensions to either `0` (minimum index) or the maximum index. If the + number of modes is fewer than the number of dimensions, the function + recycles modes using modulo arithmetic. Default: [ options.mode ]. + + options.readonly: boolean (optional) + Boolean indicating whether an array should be read-only. + + Returns + ------- + out: ndarray + Output array. + + Examples + -------- + > var arr = {{alias:@stdlib/ndarray/array}}( [ [ 1, 2 ], [ 3, 4 ] ] ); + > var out = {{alias}}( arr ) + + + See Also + -------- + diff --git a/ndarraylike2ndarray/docs/types/index.d.ts b/ndarraylike2ndarray/docs/types/index.d.ts new file mode 100644 index 00000000..b24dd98c --- /dev/null +++ b/ndarraylike2ndarray/docs/types/index.d.ts @@ -0,0 +1,73 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +// TypeScript Version: 4.1 + +/// + +import { ArrayLike } from '@stdlib/types/array'; +import { typedndarray, Mode } from '@stdlib/types/ndarray'; + +/** +* Interface defining function options. +*/ +interface Options { + /** + * Specifies how to handle a linear index which exceeds array dimensions (default: 'throw'). + */ + mode?: Mode; + + /** + * Specifies how to handle subscripts which exceed array dimensions on a per dimension basis (default: ['throw']). + */ + submode?: ArrayLike; + + /** + * Boolean indicating whether an array should be read-only. + */ + readonly?: boolean; +} + +/** +* Converts an ndarray-like object to an ndarray. +* +* ## Notes +* +* - If provided a read-only ndarray, the function returns a read-only ndarray. +* +* @param x - input ndarray +* @param options - function options +* @param options.mode - specifies how to handle indices which exceed array dimensions (default: 'throw') +* @param options.submode - specifies how to handle subscripts which exceed array dimensions on a per dimension basis (default: ['throw']) +* @param options.readonly - specifies whether an array should be read-only +* @returns ndarray +* +* @example +* var array = require( '@stdlib/ndarray/array' ); +* +* var x = array( [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] ); +* +* var out = ndarraylike2ndarray( x ); +* // returns +*/ +declare function ndarraylike2ndarray( x: typedndarray, options?: Options ): typedndarray; + + +// EXPORTS // + +export = ndarraylike2ndarray; diff --git a/ndarraylike2ndarray/docs/types/test.ts b/ndarraylike2ndarray/docs/types/test.ts new file mode 100644 index 00000000..26e102dd --- /dev/null +++ b/ndarraylike2ndarray/docs/types/test.ts @@ -0,0 +1,141 @@ +/* +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/// + +import { typedndarray } from '@stdlib/types/ndarray'; +import ndarraylike2ndarray = require( './index' ); + +/** +* Mock function to create an ndarray-like object. +* +* @return ndarray-like object +*/ +function array(): typedndarray { + const obj: typedndarray = { + 'byteLength': 80, + 'BYTES_PER_ELEMENT': 8, + 'data': new Float64Array( 10 ), + 'dtype': 'float64', + 'flags': { + 'ROW_MAJOR_CONTIGUOUS': true, + 'COLUMN_MAJOR_CONTIGUOUS': false + }, + 'length': 10, + 'ndims': 1, + 'offset': 0, + 'order': 'row-major', + 'shape': [ 10 ], + 'strides': [ 1 ], + 'get': (): number => 0, + 'set': (): typedndarray => obj + }; + return obj; +} + + +// TESTS // + +// The function returns an ndarray... +{ + const x = array(); + + ndarraylike2ndarray( x ); // $ExpectType typedndarray + ndarraylike2ndarray( x, {} ); // $ExpectType typedndarray +} + +// The compiler throws an error if the function is not provided an ndarray... +{ + ndarraylike2ndarray( '5' ); // $ExpectError + ndarraylike2ndarray( 123 ); // $ExpectError + ndarraylike2ndarray( true ); // $ExpectError + ndarraylike2ndarray( false ); // $ExpectError + ndarraylike2ndarray( null ); // $ExpectError + ndarraylike2ndarray( [] ); // $ExpectError + ndarraylike2ndarray( {} ); // $ExpectError + ndarraylike2ndarray( ( x: number ): number => x ); // $ExpectError + + ndarraylike2ndarray( '5', {} ); // $ExpectError + ndarraylike2ndarray( 123, {} ); // $ExpectError + ndarraylike2ndarray( true, {} ); // $ExpectError + ndarraylike2ndarray( false, {} ); // $ExpectError + ndarraylike2ndarray( null, {} ); // $ExpectError + ndarraylike2ndarray( [], {} ); // $ExpectError + ndarraylike2ndarray( {}, {} ); // $ExpectError + ndarraylike2ndarray( ( x: number ): number => x, {} ); // $ExpectError +} + +// The compiler throws an error if the function is not provided an object... +{ + const x = array(); + + ndarraylike2ndarray( x, '5' ); // $ExpectError + ndarraylike2ndarray( x, 123 ); // $ExpectError + ndarraylike2ndarray( x, true ); // $ExpectError + ndarraylike2ndarray( x, false ); // $ExpectError + ndarraylike2ndarray( x, null ); // $ExpectError + ndarraylike2ndarray( x, [] ); // $ExpectError + ndarraylike2ndarray( x, ( x: number ): number => x ); // $ExpectError +} + +// The compiler throws an error if the function is provided an invalid `mode` option... +{ + const x = array(); + + ndarraylike2ndarray( x, { 'mode': '5' } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': 123 } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': true } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': false } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': null } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': [] } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': {} } ); // $ExpectError + ndarraylike2ndarray( x, { 'mode': ( x: number ): number => x } ); // $ExpectError +} + +// The compiler throws an error if the function is provided an invalid `submode` option... +{ + const x = array(); + + ndarraylike2ndarray( x, { 'submode': '5' } ); // $ExpectError + ndarraylike2ndarray( x, { 'submode': 123 } ); // $ExpectError + ndarraylike2ndarray( x, { 'submode': true } ); // $ExpectError + ndarraylike2ndarray( x, { 'submode': false } ); // $ExpectError + ndarraylike2ndarray( x, { 'submode': null } ); // $ExpectError + ndarraylike2ndarray( x, { 'submode': {} } ); // $ExpectError + ndarraylike2ndarray( x, { 'submode': ( x: number ): number => x } ); // $ExpectError +} + +// The compiler throws an error if the function is provided an invalid `readonly` option... +{ + const x = array(); + + ndarraylike2ndarray( x, { 'readonly': '5' } ); // $ExpectError + ndarraylike2ndarray( x, { 'readonly': 123 } ); // $ExpectError + ndarraylike2ndarray( x, { 'readonly': null } ); // $ExpectError + ndarraylike2ndarray( x, { 'readonly': [] } ); // $ExpectError + ndarraylike2ndarray( x, { 'readonly': {} } ); // $ExpectError + ndarraylike2ndarray( x, { 'readonly': ( x: number ): number => x } ); // $ExpectError +} + +// The compiler throws an error if the function is provided an unsupported number of arguments... +{ + const x = array(); + + ndarraylike2ndarray(); // $ExpectError + ndarraylike2ndarray( x, 5, {}, {} ); // $ExpectError +} diff --git a/ndarraylike2ndarray/examples/index.js b/ndarraylike2ndarray/examples/index.js new file mode 100644 index 00000000..c2322c1b --- /dev/null +++ b/ndarraylike2ndarray/examples/index.js @@ -0,0 +1,38 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +var array = require( './../../array' ); +var ndarraylike2ndarray = require( './../lib' ); + +// Create an ndarray: +var x = array( [ [ 1, 2 ], [ 3, 4 ] ] ); + +// Create another ndarray sharing the same data: +var out = ndarraylike2ndarray( x ); +// returns + +// Print various properties: +console.log( 'dtype: %s', out.dtype ); +console.log( 'ndims: %d', out.shape.length ); +console.log( 'length: %d', out.length ); +console.log( 'shape: [ %s ]', out.shape.join( ', ' ) ); +console.log( 'strides: [ %s ]', out.strides.join( ', ' ) ); +console.log( 'offset: %d', out.offset ); +console.log( 'order: %s', out.order ); diff --git a/ndarraylike2ndarray/lib/index.js b/ndarraylike2ndarray/lib/index.js new file mode 100644 index 00000000..b55cb685 --- /dev/null +++ b/ndarraylike2ndarray/lib/index.js @@ -0,0 +1,43 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +/** +* Convert an ndarray-like object to an ndarray. +* +* @module @stdlib/ndarray/ndarraylike2ndarray +* +* @example +* var array = require( '@stdlib/ndarray/array' ); +* var ndarraylike2ndarray = require( '@stdlib/ndarray/ndarraylike2ndarray' ); +* +* var x = array( [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] ); +* +* var out = ndarraylike2ndarray( x ); +* // returns +*/ + +// MODULES // + +var main = require( './main.js' ); + + +// EXPORTS // + +module.exports = main; diff --git a/ndarraylike2ndarray/lib/main.js b/ndarraylike2ndarray/lib/main.js new file mode 100644 index 00000000..63832328 --- /dev/null +++ b/ndarraylike2ndarray/lib/main.js @@ -0,0 +1,100 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var isReadOnly = require( './../../base/assert/is-read-only' ); +var getDType = require( './../../dtype' ); +var getShape = require( './../../shape' ); +var getStrides = require( './../../strides' ); +var getOffset = require( './../../offset' ); +var getOrder = require( './../../order' ); +var getData = require( './../../data-buffer' ); +var ndarray = require( './../../ctor' ); +var defaults = require( './../../defaults' ); + + +// VARIABLES // + +var DEFAULT_ORDER = defaults( 'order' ); + + +// MAIN // + +/** +* Converts an ndarray-like object to an ndarray. +* +* @param {ndarrayLike} x - ndarray-like object +* @param {string} x.dtype - data type +* @param {Collection} x.data - data buffer +* @param {NonNegativeIntegerArray} x.shape - dimensions +* @param {IntegerArray} x.strides - stride lengths +* @param {NonNegativeInteger} x.offset - index offset +* @param {string} x.order - specifies whether `x` is row-major (C-style) or column-major (Fortran-style) +* @param {Options} [options] - function options +* @param {string} [options.mode="throw"] - specifies how to handle indices which exceed array dimensions +* @param {StringArray} [options.submode=["throw"]] - specifies how to handle subscripts which exceed array dimensions on a per dimension basis +* @param {boolean} [options.readonly=false] - boolean indicating whether an array should be read-only +* @throws {Error} cannot write to a read-only array +* @returns {ndarray} ndarray +* +* @example +* var array = require( '@stdlib/ndarray/array' ); +* +* var x = array( [ [ 1, 2, 3 ], [ 4, 5, 6 ] ] ); +* +* var out = ndarraylike2ndarray( x ); +* // returns +*/ +function ndarraylike2ndarray( x ) { + var strides; + var offset; + var order; + var shape; + var data; + var opts; + var dt; + + dt = getDType( x ); + data = getData( x ); + shape = getShape( x ); + strides = getStrides( x ); + offset = getOffset( x ); + order = getOrder( x ) || DEFAULT_ORDER; + if ( arguments.length > 1 ) { + opts = arguments[ 1 ]; + } else { + opts = {}; + } + if ( isReadOnly( x ) ) { + if ( opts.readonly === void 0 ) { + // Preserve read-only behavior... + opts.readonly = true; + } else if ( opts.readonly === false ) { + throw new Error( 'invalid argument. Cannot write to a read-only array.' ); + } + } + return new ndarray( dt, data, shape, strides, offset, order, opts ); +} + + +// EXPORTS // + +module.exports = ndarraylike2ndarray; diff --git a/ndarraylike2ndarray/package.json b/ndarraylike2ndarray/package.json new file mode 100644 index 00000000..510a8cd9 --- /dev/null +++ b/ndarraylike2ndarray/package.json @@ -0,0 +1,66 @@ +{ + "name": "@stdlib/ndarray/ndarraylike2ndarray", + "version": "0.0.0", + "description": "Convert an ndarray-like object to an ndarray.", + "license": "Apache-2.0", + "author": { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + }, + "contributors": [ + { + "name": "The Stdlib Authors", + "url": "https://github.com/stdlib-js/stdlib/graphs/contributors" + } + ], + "main": "./lib", + "directories": { + "benchmark": "./benchmark", + "doc": "./docs", + "example": "./examples", + "lib": "./lib", + "test": "./test" + }, + "types": "./docs/types", + "scripts": {}, + "homepage": "https://github.com/stdlib-js/stdlib", + "repository": { + "type": "git", + "url": "git://github.com/stdlib-js/stdlib.git" + }, + "bugs": { + "url": "https://github.com/stdlib-js/stdlib/issues" + }, + "dependencies": {}, + "devDependencies": {}, + "engines": { + "node": ">=0.10.0", + "npm": ">2.7.0" + }, + "os": [ + "aix", + "darwin", + "freebsd", + "linux", + "macos", + "openbsd", + "sunos", + "win32", + "windows" + ], + "keywords": [ + "stdlib", + "stdtypes", + "types", + "ndarray", + "standardize", + "multidimensional", + "array", + "convert", + "utilities", + "utility", + "utils", + "util" + ], + "__stdlib__": {} +} diff --git a/ndarraylike2ndarray/test/test.js b/ndarraylike2ndarray/test/test.js new file mode 100644 index 00000000..58837762 --- /dev/null +++ b/ndarraylike2ndarray/test/test.js @@ -0,0 +1,243 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2024 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var Float64Array = require( '@stdlib/array/float64' ); +var array = require( './../../array' ); +var ndarray = require( './../../ctor' ); +var isReadOnly = require( './../../base/assert/is-read-only' ); +var ndarraylike2ndarray = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.strictEqual( typeof ndarraylike2ndarray, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'the function throws an error if provided a `readonly` option equal to `true` when the first argument is a read-only ndarray', function test( t ) { + var xbuf; + var x; + + xbuf = new Float64Array( 10 ); + x = array( xbuf, { + 'readonly': true + }); + + t.throws( badValue, Error, 'throws an error' ); + t.end(); + + function badValue() { + ndarraylike2ndarray( x, { + 'readonly': false + }); + } +}); + +tape( 'the function converts an ndarray-like object to an ndarray (ndarray)', function test( t ) { + var expected; + var actual; + var xbuf; + var x; + + xbuf = new Float64Array( 10 ); + x = array( xbuf ); + + expected = { + 'data': x.data, + 'dtype': x.dtype, + 'length': x.length, + 'shape': x.shape, + 'strides': x.strides, + 'offset': x.offset, + 'order': x.order + }; + actual = ndarraylike2ndarray( x ); + + t.strictEqual( actual instanceof ndarray, true, 'returns expected value' ); + t.strictEqual( actual.data, expected.data, 'returns expected value' ); + t.strictEqual( actual.dtype, expected.dtype, 'returns expected value' ); + t.strictEqual( actual.length, expected.length, 'returns expected value' ); + t.deepEqual( actual.shape, expected.shape, 'returns expected value' ); + t.deepEqual( actual.strides, expected.strides, 'returns expected value' ); + t.strictEqual( actual.offset, expected.offset, 'returns expected value' ); + t.strictEqual( actual.order, expected.order, 'returns expected value' ); + t.strictEqual( isReadOnly( actual ), false, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function converts an ndarray-like object to an ndarray (ndarray-like)', function test( t ) { + var expected; + var actual; + var xbuf; + var x; + + xbuf = new Float64Array( 10 ); + x = { + 'data': xbuf, + 'dtype': 'float64', + 'length': 10, + 'shape': [ 2, 5 ], + 'strides': [ 5, 1 ], + 'offset': 0, + 'order': 'row-major' + }; + + expected = { + 'data': x.data, + 'dtype': x.dtype, + 'length': x.length, + 'shape': x.shape, + 'strides': x.strides, + 'offset': x.offset, + 'order': x.order + }; + actual = ndarraylike2ndarray( x ); + + t.strictEqual( actual instanceof ndarray, true, 'returns expected value' ); + t.strictEqual( actual.data, expected.data, 'returns expected value' ); + t.strictEqual( actual.dtype, expected.dtype, 'returns expected value' ); + t.strictEqual( actual.length, expected.length, 'returns expected value' ); + t.deepEqual( actual.shape, expected.shape, 'returns expected value' ); + t.deepEqual( actual.strides, expected.strides, 'returns expected value' ); + t.strictEqual( actual.offset, expected.offset, 'returns expected value' ); + t.strictEqual( actual.order, expected.order, 'returns expected value' ); + t.strictEqual( isReadOnly( actual ), false, 'returns expected value' ); + + t.end(); +}); + +tape( 'by default, the function returns a read-only ndarray if provided a read-only ndarray (ndarray)', function test( t ) { + var expected; + var actual; + var xbuf; + var x; + + xbuf = new Float64Array( 10 ); + x = array( xbuf, { + 'readonly': true + }); + + expected = { + 'data': x.data, + 'dtype': x.dtype, + 'length': x.length, + 'shape': x.shape, + 'strides': x.strides, + 'offset': x.offset, + 'order': x.order + }; + actual = ndarraylike2ndarray( x ); + + t.strictEqual( actual instanceof ndarray, true, 'returns expected value' ); + t.strictEqual( actual.data, expected.data, 'returns expected value' ); + t.strictEqual( actual.dtype, expected.dtype, 'returns expected value' ); + t.strictEqual( actual.length, expected.length, 'returns expected value' ); + t.deepEqual( actual.shape, expected.shape, 'returns expected value' ); + t.deepEqual( actual.strides, expected.strides, 'returns expected value' ); + t.strictEqual( actual.offset, expected.offset, 'returns expected value' ); + t.strictEqual( actual.order, expected.order, 'returns expected value' ); + t.strictEqual( isReadOnly( actual ), true, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function supports ndarray options (ndarray)', function test( t ) { + var expected; + var actual; + var xbuf; + var x; + + xbuf = new Float64Array( 10 ); + x = array( xbuf ); + + expected = { + 'data': x.data, + 'dtype': x.dtype, + 'length': x.length, + 'shape': x.shape, + 'strides': x.strides, + 'offset': x.offset, + 'order': x.order + }; + actual = ndarraylike2ndarray( x, { + 'readonly': false + }); + + t.strictEqual( actual instanceof ndarray, true, 'returns expected value' ); + t.strictEqual( actual.data, expected.data, 'returns expected value' ); + t.strictEqual( actual.dtype, expected.dtype, 'returns expected value' ); + t.strictEqual( actual.length, expected.length, 'returns expected value' ); + t.deepEqual( actual.shape, expected.shape, 'returns expected value' ); + t.deepEqual( actual.strides, expected.strides, 'returns expected value' ); + t.strictEqual( actual.offset, expected.offset, 'returns expected value' ); + t.strictEqual( actual.order, expected.order, 'returns expected value' ); + t.strictEqual( isReadOnly( actual ), false, 'returns expected value' ); + + t.end(); +}); + +tape( 'the function supports ndarray options (ndarray-like)', function test( t ) { + var expected; + var actual; + var xbuf; + var x; + + xbuf = new Float64Array( 10 ); + x = { + 'data': xbuf, + 'dtype': 'float64', + 'length': 10, + 'shape': [ 2, 5 ], + 'strides': [ 5, 1 ], + 'offset': 0, + 'order': 'row-major' + }; + + expected = { + 'data': x.data, + 'dtype': x.dtype, + 'length': x.length, + 'shape': x.shape, + 'strides': x.strides, + 'offset': x.offset, + 'order': x.order + }; + actual = ndarraylike2ndarray( x, { + 'readonly': false + }); + + t.strictEqual( actual instanceof ndarray, true, 'returns expected value' ); + t.strictEqual( actual.data, expected.data, 'returns expected value' ); + t.strictEqual( actual.dtype, expected.dtype, 'returns expected value' ); + t.strictEqual( actual.length, expected.length, 'returns expected value' ); + t.deepEqual( actual.shape, expected.shape, 'returns expected value' ); + t.deepEqual( actual.strides, expected.strides, 'returns expected value' ); + t.strictEqual( actual.offset, expected.offset, 'returns expected value' ); + t.strictEqual( actual.order, expected.order, 'returns expected value' ); + t.strictEqual( isReadOnly( actual ), false, 'returns expected value' ); + + t.end(); +});