Skip to content

feat: add stats/incr/nanmcovariance #6865

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 2 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat(stats/incr/nanmcovariance): add nanmcovariance to the stats/incr…
…/* namespace

This commit adds the `nanmcovariance` module to the `stats/incr/*` namespace, providing a way to compute a moving unbiased sample covariance incrementally,
while handling NaN values. This commit was made to address Issue #5567 and as suggested in the issue, it is based on a thin wrapper around wmean, similar
to the relationship between nansum and sum, mainting API consistency and design. This commit includes appropriate documentation and tests
for the new purpose of the package, styles of which are consistent to the stats/incr/* namespace.

Fixes: #5567 [RFC]
Private-ref: #5567
Authored-by: Don Chacko <donisepic30@gmail.com>
  • Loading branch information
SergeantQuickscoper committed Apr 29, 2025
commit 697083136a77c006b7816dddccb1330c6c7cb06f
186 changes: 186 additions & 0 deletions lib/node_modules/@stdlib/stats/incr/nanmcovariance/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
<!--

@license Apache-2.0

Copyright (c) 2025 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.

-->

# incrnanmcovariance

> Compute a moving [unbiased sample covariance][covariance] incrementally, while handling NaN values.

<section class="intro">

For unknown population means, the [unbiased sample covariance][covariance] for a window `n` of size `W` is defined as

<!-- <equation class="equation" label="eq:unbiased_sample_covariance_unknown_means" align="center" raw="\operatorname{cov_n} = \frac{1}{n-1} \sum_{i=j}^{j+W-1} (x_i - \bar{x}_n)(y_i - \bar{y}_n)" alt="Equation for the unbiased sample covariance for unknown population means."> -->

```math
\mathop{\mathrm{cov_n}} = \frac{1}{n-1} \sum_{i=j}^{j+W-1} (x_i - \bar{x}_n)(y_i - \bar{y}_n)
```

<!-- <div class="equation" align="center" data-raw-text="\operatorname{cov_n} = \frac{1}{n-1} \sum_{i=j}^{j+W-1} (x_i - \bar{x}_n)(y_i - \bar{y}_n)" data-equation="eq:unbiased_sample_covariance_unknown_means">
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@49d8cabda84033d55d7b8069f19ee3dd8b8d1496/lib/node_modules/@stdlib/stats/incr/mcovariance/docs/img/equation_unbiased_sample_covariance_unknown_means.svg" alt="Equation for the unbiased sample covariance for unknown population means.">
<br>
</div> -->

<!-- </equation> -->

where `j` specifies the index of the value at which the window begins. For example, for a trailing (i.e., non-centered) window using zero-based indexing and `j` greater than or equal to `W`, `j` is the `n-W`th value with `n` being the number of values thus analyzed.

For known population means, the [unbiased sample covariance][covariance] for a window `n` of size `W` is defined as

<!-- <equation class="equation" label="eq:unbiased_sample_covariance_known_means" align="center" raw="\operatorname{cov_n} = \frac{1}{n} \sum_{i=j}^{j+W-1} (x_i - \mu_x)(y_i - \mu_y)" alt="Equation for the unbiased sample covariance for known population means."> -->

```math
\mathop{\mathrm{cov_n}} = \frac{1}{n} \sum_{i=j}^{j+W-1} (x_i - \mu_x)(y_i - \mu_y)
```

<!-- <div class="equation" align="center" data-raw-text="\operatorname{cov_n} = \frac{1}{n} \sum_{i=j}^{j+W-1} (x_i - \mu_x)(y_i - \mu_y)" data-equation="eq:unbiased_sample_covariance_known_means">
<img src="https://cdn.jsdelivr.net/gh/stdlib-js/stdlib@27e2a43c70db648bb5bbc3fd0cdee050c25adc0b/lib/node_modules/@stdlib/stats/incr/mcovariance/docs/img/equation_unbiased_sample_covariance_known_means.svg" alt="Equation for the unbiased sample covariance for known population means.">
<br>
</div> -->

<!-- </equation> -->

</section>

<!-- /.intro -->

<section class="usage">

## Usage

```javascript
var incrnanmcovariance = require( '@stdlib/stats/incr/nanmcovariance' );
```

#### incrnanmcovariance( window\[, mx, my] )

Returns an accumulator `function` which incrementally computes a moving [unbiased sample covariance][covariance]. The `window` parameter defines the number of values over which to compute the moving [unbiased sample covariance][covariance].

```javascript
var accumulator = incrnanmcovariance( 3 );
```

If means are already known, provide `mx` and `my` arguments.

```javascript
var accumulator = incrnanmcovariance( 3, 5.0, -3.14 );
```

#### accumulator( \[x, y] )

If provided input values `x` and `y`, the accumulator function returns an updated [unbiased sample covariance][covariance]. If not provided input values `x` and `y`, the accumulator function returns the current [unbiased sample covariance][covariance].

```javascript
var accumulator = incrnanmcovariance( 3 );

var v = accumulator();
// returns null

// Fill the window...
v = accumulator( 2.0, 1.0 ); // [(2.0, 1.0)]
// returns 0.0

v = accumulator( -5.0, 3.14 ); // [(2.0, 1.0), (-5.0, 3.14)]
// returns ~-7.49

v = accumulator( 3.0, -1.0 ); // [(2.0, 1.0), (-5.0, 3.14), (3.0, -1.0)]
// returns -8.35

// Window begins sliding...
v = accumulator( 5.0, -9.5 ); // [(-5.0, 3.14), (3.0, -1.0), (5.0, -9.5)]
// returns -29.42

v = accumulator( -5.0, 1.5 ); // [(3.0, -1.0), (5.0, -9.5), (-5.0, 1.5)]
// returns -24.5

v = accumulator();
// returns -24.5
```

</section>

<!-- /.usage -->


<section class="examples">

## Examples

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

```javascript
var randu = require( '@stdlib/random/base/randu' );
var incrnanmcovariance = require( '@stdlib/stats/incr/nanmcovariance' );

var accumulator;
var x;
var y;
var i;

// Initialize an accumulator:
accumulator = incrnanmcovariance( 5 );

// For each simulated datum, update the moving unbiased sample covariance...
for ( i = 0; i < 100; i++ ) {
x = randu() * 100.0;
y = randu() * 100.0;
accumulator( x, y );
}
console.log( accumulator() );
```

</section>

<!-- /.examples -->

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

<section class="related">

* * *

## See Also

- <span class="package-name">[`@stdlib/stats/incr/covariance`][@stdlib/stats/incr/covariance]</span><span class="delimiter">: </span><span class="description">compute an unbiased sample covariance incrementally.</span>
- <span class="package-name">[`@stdlib/stats/incr/mpcorr`][@stdlib/stats/incr/mpcorr]</span><span class="delimiter">: </span><span class="description">compute a moving sample Pearson product-moment correlation coefficient incrementally.</span>
- <span class="package-name">[`@stdlib/stats/incr/mvariance`][@stdlib/stats/incr/mvariance]</span><span class="delimiter">: </span><span class="description">compute a moving unbiased sample variance incrementally.</span>

</section>

<!-- /.related -->

<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="links">

[covariance]: https://en.wikipedia.org/wiki/Covariance

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

[@stdlib/stats/incr/covariance]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/incr/covariance

[@stdlib/stats/incr/mpcorr]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/incr/mpcorr

[@stdlib/stats/incr/mcovariance]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/stats/incr/mcovariance

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

</section>

<!-- /.links -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
/**
* @license Apache-2.0
*
* Copyright (c) 2025 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 randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pkg = require( './../package.json' ).name;
var incrnanmcovariance = require( './../lib' );


// MAIN //

bench( pkg, function benchmark( b ) {
var f;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
f = incrnanmcovariance( (i%5)+1 );
if ( typeof f !== 'function' ) {
b.fail( 'should return a function' );
}
}
b.toc();
if ( typeof f !== 'function' ) {
b.fail( 'should return a function' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( pkg+'::accumulator', function benchmark( b ) {
var acc;
var v;
var i;

acc = incrnanmcovariance( 5 );

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = acc( randu(), randu() );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( pkg+'::accumulator,unknown_means', function benchmark( b ) {
var acc;
var v;
var i;

acc = incrnanmcovariance( 5 );

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = acc( randu(), randu() );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( pkg+'::accumulator,known_means', function benchmark( b ) {
var acc;
var v;
var i;

acc = incrnanmcovariance( 5, 3.0, -1.0 );

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = acc( randu(), randu() );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
Loading