Skip to content

feat: refactor and add accessor protocol support to stats/base/nanvariancetk #6025

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

Merged
merged 4 commits into from
Apr 30, 2025
Merged
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
57 changes: 26 additions & 31 deletions lib/node_modules/@stdlib/stats/base/nanvariancetk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ The use of the term `n-1` is commonly referred to as Bessel's correction. Note,
var nanvariancetk = require( '@stdlib/stats/base/nanvariancetk' );
```

#### nanvariancetk( N, correction, x, stride )
#### nanvariancetk( N, correction, x, strideX )

Computes the [variance][variance] of a strided array `x` ignoring `NaN` values and using a one-pass textbook algorithm.
Computes the [variance][variance] of a strided array ignoring `NaN` values and using a one-pass textbook algorithm.

```javascript
var x = [ 1.0, -2.0, NaN, 2.0 ];
Expand All @@ -114,38 +114,32 @@ The function has the following parameters:
- **N**: number of indexed elements.
- **correction**: degrees of freedom adjustment. Setting this parameter to a value other than `0` has the effect of adjusting the divisor during the calculation of the [variance][variance] according to `n-c` where `c` corresponds to the provided degrees of freedom adjustment and `n` corresponds to the number of non-`NaN` indexed elements. When computing the [variance][variance] of a population, setting this parameter to `0` is the standard choice (i.e., the provided array contains data constituting an entire population). When computing the unbiased sample [variance][variance], setting this parameter to `1` is the standard choice (i.e., the provided array contains data sampled from a larger population; this is commonly referred to as Bessel's correction).
- **x**: input [`Array`][mdn-array] or [`typed array`][mdn-typed-array].
- **stride**: index increment for `x`.
- **strideX**: stride length for `x`.

The `N` and `stride` parameters determine which elements in `x` are accessed at runtime. For example, to compute the [variance][variance] of every other element in `x`,
The `N` and stride parameters determine which elements in the strided array are accessed at runtime. For example, to compute the [variance][variance] of every other element in `x`,

```javascript
var floor = require( '@stdlib/math/base/special/floor' );

var x = [ 1.0, 2.0, 2.0, -7.0, -2.0, 3.0, 4.0, 2.0, NaN ];
var N = floor( x.length / 2 );

var v = nanvariancetk( N, 1, x, 2 );
var v = nanvariancetk( 5, 1, x, 2 );
// returns 6.25
```

Note that indexing is relative to the first index. To introduce an offset, use [`typed array`][mdn-typed-array] views.

<!-- eslint-disable stdlib/capitalized-comments -->
<!-- eslint-disable stdlib/capitalized-comments, max-len -->

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var floor = require( '@stdlib/math/base/special/floor' );

var x0 = new Float64Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN ] );
var x0 = new Float64Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ] );
var x1 = new Float64Array( x0.buffer, x0.BYTES_PER_ELEMENT*1 ); // start at 2nd element

var N = floor( x0.length / 2 );

var v = nanvariancetk( N, 1, x1, 2 );
var v = nanvariancetk( 5, 1, x1, 2 );
// returns 6.25
```

#### nanvariancetk.ndarray( N, correction, x, stride, offset )
#### nanvariancetk.ndarray( N, correction, x, strideX, offsetX )

Computes the [variance][variance] of a strided array ignoring `NaN` values and using a one-pass textbook algorithm and alternative indexing semantics.

Expand All @@ -158,17 +152,14 @@ var v = nanvariancetk.ndarray( x.length, 1, x, 1, 0 );

The function has the following additional parameters:

- **offset**: starting index for `x`.
- **offsetX**: starting index for `x`.

While [`typed array`][mdn-typed-array] views mandate a view offset based on the underlying `buffer`, the `offset` parameter supports indexing semantics based on a starting index. For example, to calculate the [variance][variance] for every other value in `x` starting from the second value
While [`typed array`][mdn-typed-array] views mandate a view offset based on the underlying buffer, the offset parameter supports indexing semantics based on a starting index. For example, to calculate the [variance][variance] for every other element in the strided array starting from the second element

```javascript
var floor = require( '@stdlib/math/base/special/floor' );
var x = [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0, NaN, NaN ];

var x = [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ];
var N = floor( x.length / 2 );

var v = nanvariancetk.ndarray( N, 1, x, 2, 1 );
var v = nanvariancetk.ndarray( 5, 1, x, 2, 1 );
// returns 6.25
```

Expand All @@ -181,6 +172,7 @@ var v = nanvariancetk.ndarray( N, 1, x, 2, 1 );
## Notes

- If `N <= 0`, both functions return `NaN`.
- Both functions support array-like objects having getter and setter accessors for array element access (e.g., [`@stdlib/array/base/accessor`][@stdlib/array/base/accessor]).
- If `n - c` is less than or equal to `0` (where `c` corresponds to the provided degrees of freedom adjustment and `n` corresponds to the number of non-`NaN` indexed elements), both functions return `NaN`.
- Some caution should be exercised when using the one-pass textbook algorithm. Literature overwhelmingly discourages the algorithm's use for two reasons: 1) the lack of safeguards against underflow and overflow and 2) the risk of catastrophic cancellation when subtracting the two sums if the sums are large and the variance small. These concerns have merit; however, the one-pass textbook algorithm should not be dismissed outright. For data distributions with a moderately large standard deviation to mean ratio (i.e., **coefficient of variation**), the one-pass textbook algorithm may be acceptable, especially when performance is paramount and some precision loss is acceptable (including a risk of returning a negative variance due to floating-point rounding errors!). In short, no single "best" algorithm for computing the variance exists. The "best" algorithm depends on the underlying data distribution, your performance requirements, and your minimum precision requirements. When evaluating which algorithm to use, consider the relative pros and cons, and choose the algorithm which best serves your needs.
- Depending on the environment, the typed versions ([`dnanvariancetk`][@stdlib/stats/base/dnanvariancetk], [`snanvariancetk`][@stdlib/stats/base/snanvariancetk], etc.) are likely to be significantly more performant.
Expand All @@ -196,18 +188,19 @@ var v = nanvariancetk.ndarray( N, 1, x, 2, 1 );
<!-- eslint no-undef: "error" -->

```javascript
var randu = require( '@stdlib/random/base/randu' );
var round = require( '@stdlib/math/base/special/round' );
var Float64Array = require( '@stdlib/array/float64' );
var uniform = require( '@stdlib/random/base/uniform' );
var filledarrayBy = require( '@stdlib/array/filled-by' );
var nanvariancetk = require( '@stdlib/stats/base/nanvariancetk' );
var bernoulli = require( '@stdlib/random/base/bernoulli' );

var x;
var i;

x = new Float64Array( 10 );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = round( (randu()*100.0) - 50.0 );
function rand() {
if ( bernoulli( 0.8 ) < 1 ) {
return NaN;
}
return uniform( -50.0, 50.0 );
}

var x = filledarrayBy( 10, 'float64', rand );
console.log( x );

var v = nanvariancetk( x.length, 1, x, 1 );
Expand Down Expand Up @@ -258,6 +251,8 @@ console.log( v );

[mdn-typed-array]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

[@stdlib/array/base/accessor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/array/base/accessor

[@ling:1974a]: https://doi.org/10.2307/2286154

<!-- <related-links> -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,30 @@
// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var uniform = require( '@stdlib/random/base/uniform' );
var bernoulli = require( '@stdlib/random/base/bernoulli' );
var filledarrayBy = require( '@stdlib/array/filled-by' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var pkg = require( './../package.json' ).name;
var nanvariancetk = require( './../lib/nanvariancetk.js' );
var nanvariancetk = require( './../lib/main.js' );


// FUNCTIONS //

/**
* Returns a random value or `NaN`.
*
* @private
* @returns {number} random number or `NaN`
*/
function rand() {
if ( bernoulli( 0.8 ) < 1 ) {
return NaN;
}
return uniform( -10.0, 10.0 );
}

/**
* Creates a benchmark function.
*
Expand All @@ -38,17 +53,7 @@ var nanvariancetk = require( './../lib/nanvariancetk.js' );
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;

x = [];
for ( i = 0; i < len; i++ ) {
if ( randu() < 0.2 ) {
x.push( NaN );
} else {
x.push( ( randu()*20.0 ) - 10.0 );
}
}
var x = filledarrayBy( len, 'float64', rand );
return benchmark;

function benchmark( b ) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
// MODULES //

var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var uniform = require( '@stdlib/random/base/uniform' );
var bernoulli = require( '@stdlib/random/base/bernoulli' );
var filledarrayBy = require( '@stdlib/array/filled-by' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var pkg = require( './../package.json' ).name;
Expand All @@ -30,6 +32,19 @@ var nanvariancetk = require( './../lib/ndarray.js' );

// FUNCTIONS //

/**
* Returns a random value or `NaN`.
*
* @private
* @returns {number} random number or `NaN`
*/
function rand() {
if ( bernoulli( 0.8 ) < 1 ) {
return NaN;
}
return uniform( -10.0, 10.0 );
}

/**
* Creates a benchmark function.
*
Expand All @@ -38,17 +53,7 @@ var nanvariancetk = require( './../lib/ndarray.js' );
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;

x = [];
for ( i = 0; i < len; i++ ) {
if ( randu() < 0.2 ) {
x.push( NaN );
} else {
x.push( ( randu()*20.0 ) - 10.0 );
}
}
var x = filledarrayBy( len, 'float64', rand );
return benchmark;

function benchmark( b ) {
Expand Down
38 changes: 17 additions & 21 deletions lib/node_modules/@stdlib/stats/base/nanvariancetk/docs/repl.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@

{{alias}}( N, correction, x, stride )
{{alias}}( N, correction, x, strideX )
Computes the variance of a strided array ignoring `NaN` values and using a
one-pass textbook algorithm.

The `N` and `stride` parameters determine which elements in `x` are accessed
at runtime.
The `N` and `stride` parameters determine which elements in the strided
array are accessed at runtime.

Indexing is relative to the first index. To introduce an offset, use a typed
array view.
Expand Down Expand Up @@ -34,8 +34,8 @@
x: Array<number>|TypedArray
Input array.

stride: integer
Index increment.
strideX: integer
Stride length.

Returns
-------
Expand All @@ -49,22 +49,19 @@
> {{alias}}( x.length, 1, x, 1 )
~4.3333

// Using `N` and `stride` parameters:
> x = [ -2.0, 1.0, 1.0, -5.0, 2.0, -1.0 ];
> var N = {{alias:@stdlib/math/base/special/floor}}( x.length / 2 );
> var stride = 2;
> {{alias}}( N, 1, x, stride )
// Using `N` and stride parameters:
> x = [ -2.0, 1.0, 1.0, -5.0, 2.0, -1.0, NaN ];
> {{alias}}( 4, 1, x, 2 )
~4.3333

// Using view offsets:
> var x0 = new {{alias:@stdlib/array/float64}}( [ 1.0, -2.0, 3.0, 2.0, 5.0, -1.0 ] );
> var x0 = new {{alias:@stdlib/array/float64}}( [ 1.0, -2.0, 3.0, 2.0, 5.0, -1.0, NaN, NaN ] );
> var x1 = new {{alias:@stdlib/array/float64}}( x0.buffer, x0.BYTES_PER_ELEMENT*1 );
> N = {{alias:@stdlib/math/base/special/floor}}( x0.length / 2 );
> stride = 2;
> {{alias}}( N, 1, x1, stride )
> {{alias}}( 4, 1, x1, 2 )
~4.3333

{{alias}}.ndarray( N, correction, x, stride, offset )

{{alias}}.ndarray( N, correction, x, strideX, offsetX )
Computes the variance of a strided array ignoring `NaN` values and using a
one-pass textbook algorithm and alternative indexing semantics.

Expand Down Expand Up @@ -93,10 +90,10 @@
x: Array<number>|TypedArray
Input array.

stride: integer
Index increment.
strideX: integer
Stride length.

offset: integer
offsetX: integer
Starting index.

Returns
Expand All @@ -112,9 +109,8 @@
~4.3333

// Using offset parameter:
> var x = [ 1.0, -2.0, 3.0, 2.0, 5.0, -1.0 ];
> var N = {{alias:@stdlib/math/base/special/floor}}( x.length / 2 );
> {{alias}}.ndarray( N, 1, x, 2, 1 )
> var x = [ 1.0, -2.0, 3.0, 2.0, 5.0, -1.0, NaN, NaN ];
> {{alias}}.ndarray( 4, 1, x, 2, 1 )
~4.3333

See Also
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,12 @@

/// <reference types="@stdlib/types"/>

import { NumericArray } from '@stdlib/types/array';
import { NumericArray, Collection, AccessorArrayLike } from '@stdlib/types/array';

/**
* Input array.
*/
type InputArray = NumericArray | Collection<number> | AccessorArrayLike<number>;

/**
* Interface describing `nanvariancetk`.
Expand All @@ -32,7 +37,7 @@ interface Routine {
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @param strideX - stride length
* @returns variance
*
* @example
Expand All @@ -41,16 +46,16 @@ interface Routine {
* var v = nanvariancetk( x.length, 1, x, 1 );
* // returns ~4.3333
*/
( N: number, correction: number, x: NumericArray, stride: number ): number;
( N: number, correction: number, x: InputArray, strideX: number ): number;

/**
* Computes the variance of a strided array ignoring `NaN` values and using a one-pass textbook algorithm and alternative indexing semantics.
*
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @param offset - starting index
* @param strideX - stride length
* @param offsetX - starting index
* @returns variance
*
* @example
Expand All @@ -59,7 +64,7 @@ interface Routine {
* var v = nanvariancetk.ndarray( x.length, 1, x, 1, 0 );
* // returns ~4.3333
*/
ndarray( N: number, correction: number, x: NumericArray, stride: number, offset: number ): number;
ndarray( N: number, correction: number, x: InputArray, strideX: number, offset: number ): number;
}

/**
Expand All @@ -68,7 +73,7 @@ interface Routine {
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @param strideX - stride length
* @returns variance
*
* @example
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
* limitations under the License.
*/

import AccessorArray = require( '@stdlib/array/base/accessor' );
import nanvariancetk = require( './index' );


Expand All @@ -26,6 +27,7 @@ import nanvariancetk = require( './index' );
const x = new Float64Array( 10 );

nanvariancetk( x.length, 1, x, 1 ); // $ExpectType number
nanvariancetk( x.length, 1, new AccessorArray( x ), 1 ); // $ExpectType number
}

// The compiler throws an error if the function is provided a first argument which is not a number...
Expand Down Expand Up @@ -101,6 +103,7 @@ import nanvariancetk = require( './index' );
const x = new Float64Array( 10 );

nanvariancetk.ndarray( x.length, 1, x, 1, 0 ); // $ExpectType number
nanvariancetk.ndarray( x.length, 1, new AccessorArray( x ), 1, 0 ); // $ExpectType number
}

// The compiler throws an error if the `ndarray` method is provided a first argument which is not a number...
Expand Down
Loading