Skip to content

feat: add ndarray/find #4398

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
225 changes: 225 additions & 0 deletions lib/node_modules/@stdlib/ndarray/find/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
<!--

@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.

-->

# findElement

> Return the first element in the [ndarray][@stdlib/ndarray/ctor] that passes a test implemented by a predicate function.

<section class="intro">

</section>

<!-- /.intro -->

<section class="usage">

## Usage

```javascript
var findElement = require( '@stdlib/ndarray/find' );
```

#### findElement( x\[, options], predicate\[, thisArg] )

Return the first element in the [ndarray][@stdlib/ndarray/ctor] that passes a test implemented by a predicate function.

<!-- eslint-disable no-invalid-this, max-len -->

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var ndarray2array = require( '@stdlib/ndarray/to-array' );

function predicate( z ) {
return z > 6.0;
}

var buffer = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 ] );
var shape = [ 2, 3 ];
var strides = [ 6, 1 ];
var offset = 1;

var x = ndarray( 'float64', buffer, shape, strides, offset, 'row-major' );
// returns <ndarray>

var arr = ndarray2array( x );
// returns [ [ 2.0, 3.0, 4.0 ], [ 8.0, 9.0, 10.0 ] ]

var y = findElement( x, predicate );
// returns 8.0
```

The function accepts the following arguments:

- **x**: input [ndarray][@stdlib/ndarray/ctor].
- **options**: function options _(optional)_.
- **predicate**: predicate function.
- **thisArg**: predicate function execution context _(optional)_.

The function accepts the following options:

- **order**: index iteration order. By default, the function iterates over elements according to the [layout order][@stdlib/ndarray/orders] of the provided [ndarray][@stdlib/ndarray/ctor]. Accordingly, for row-major input [ndarrays][@stdlib/ndarray/ctor], the last dimension indices increment fastest. For column-major input [ndarrays][@stdlib/ndarray/ctor], the first dimension indices increment fastest. To override the inferred order and ensure that indices increment in a specific manner, regardless of the input [ndarray][@stdlib/ndarray/ctor]'s layout order, explicitly set the iteration order. Note, however, that iterating according to an order which does not match that of the input [ndarray][@stdlib/ndarray/ctor] may, in some circumstances, result in performance degradation due to cache misses. Must be either `'row-major'` or `'column-major'`.

By default, the output element's [data type][@stdlib/ndarray/dtypes] is inferred from the input [ndarray][@stdlib/ndarray/ctor].

<!-- eslint-disable max-len -->

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var ndarray2array = require( '@stdlib/ndarray/to-array' );

function predicate( z ) {
return z > 3.0;
}

var buffer = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 ] );
var shape = [ 2, 3 ];
var strides = [ 6, 1 ];
var offset = 1;

var x = ndarray( 'float64', buffer, shape, strides, offset, 'row-major' );
// returns <ndarray>

var arr = ndarray2array( x );
// returns [ [ 2.0, 3.0, 4.0 ], [ 8.0, 9.0, 10.0 ] ]

var opts = {
'order': 'column-major'
};
var y = findElement( x, opts, predicate );
// returns 8.0

opts = {
'order': 'row-major'
};
y = findElement( x, opts, predicate );
// returns 4.0
```

To set the `predicate` function execution context, provide a `thisArg`.

<!-- eslint-disable no-invalid-this, max-len -->

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var ndarray2array = require( '@stdlib/ndarray/to-array' );

function predicate( z ) {
this.count += 1;
return z > 6.0;
}

var buffer = new Float64Array( [ 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0 ] );
var shape = [ 2, 3 ];
var strides = [ 6, 1 ];
var offset = 1;

var x = ndarray( 'float64', buffer, shape, strides, offset, 'row-major' );
// returns <ndarray>

var arr = ndarray2array( x );
// returns [ [ 2.0, 3.0, 4.0 ], [ 8.0, 9.0, 10.0 ] ]

var ctx = {
'count': 0
};
var y = findElement( x, predicate, ctx );
// returns 8.0

var count = ctx.count;
// returns 4
```

The `predicate` function is provided the following arguments:

- **value**: current array element.
- **indices**: current array element indices.
- **arr**: the input [ndarray][@stdlib/ndarray/ctor].

</section>

<!-- /.usage -->

<section class="notes">

## Notes

- The function returns **NaN** if no element in ndarray passes test implemented by the predicate function.

</section>

<!-- /.notes -->

<section class="examples">

## Examples

<!-- eslint no-undef: "error" -->

```javascript
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var ndarray2array = require( '@stdlib/ndarray/to-array' );
var naryFunction = require( '@stdlib/utils/nary-function' );
var array = require( '@stdlib/ndarray/array' );
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var findElement = require( '@stdlib/ndarray/find' );

var buffer = discreteUniform( 10, -100, 100, {
'dtype': 'generic'
});
var x = array( buffer, {
'shape': [ 5, 2 ],
'dtype': 'generic'
});
console.log( ndarray2array( x ) );

var y = findElement( x, naryFunction( isPositive, 1 ) );
console.log( y );
```

</section>

<!-- /.examples -->

<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->

<section class="related">

</section>

<!-- /.related -->

<section class="links">

[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor

[@stdlib/ndarray/dtypes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/dtypes

[@stdlib/ndarray/orders]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/orders

<!-- <related-links> -->

<!-- </related-links> -->

</section>

<!-- /.links -->
142 changes: 142 additions & 0 deletions lib/node_modules/@stdlib/ndarray/find/benchmark/benchmark.1d.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
/**
* @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 isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var isInteger = require( '@stdlib/assert/is-integer' );
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var shape2strides = require( '@stdlib/ndarray/base/shape2strides' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var pkg = require( './../package.json' ).name;
var findElement = require( './../lib' );


// VARIABLES //

var xtypes = [ 'generic' ];
var orders = [ 'row-major', 'column-major' ];


// FUNCTIONS //

/**
* Predicate function.
*
* @private
* @param {number} value - array element
* @param {NonNegativeIntegerArray} indices - element indices
* @param {ndarray} arr - input array
* @returns {boolean} result
*/
function predicate( value ) {
return value > 0.0;
}

/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @param {NonNegativeIntegerArray} shape - ndarray shape
* @param {string} xtype - input ndarray data type
* @param {string} order - ndarray memory layout
* @returns {Function} benchmark function
*/
function createBenchmark( len, shape, xtype, order ) {
var strides;
var xbuf;
var x;

xbuf = discreteUniform( len, -100, 100, {
'dtype': xtype
});
strides = shape2strides( shape, order );
x = ndarray( xtype, xbuf, shape, strides, 0, order );

return benchmark;

/**
* Benchmark function.
*
* @private
* @param {Benchmark} b - benchmark instance
*/
function benchmark( b ) {
var y;
var i;

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
y = findElement( x, predicate );
if ( isnan( y ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( !isInteger( y ) ) {
b.fail( 'should return an ndarray' );
}
b.pass( 'benchmark finished' );
b.end();
}
}


// MAIN //

/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var ord;
var sh;
var t1;
var f;
var i;
var j;
var k;

min = 1; // 10^min
max = 6; // 10^max

for ( k = 0; k < orders.length; k++ ) {
ord = orders[ k ];
for ( j = 0; j < xtypes.length; j++ ) {
t1 = xtypes[ j ];
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );

sh = [ len ];
f = createBenchmark( len, sh, t1, ord );
bench( pkg+':ndims='+sh.length+',len='+len+',shape=['+sh.join(',')+'],xorder='+ord+',yorder='+ord+',xtype='+t1, f );
}
}
}
}

main();
Loading
Loading