Skip to content

feat: add stats/base/ndarray/dcovarmtk #7692

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 4 commits 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
216 changes: 216 additions & 0 deletions lib/node_modules/@stdlib/stats/base/ndarray/dcovarmtk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
<!--

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

-->

# dcovarmtk

> Calculate the [covariance][covariance] of two one-dimensional double-precision floating-point ndarrays provided known means and using a one-pass textbook algorithm.

<section class="intro">

The population [covariance][covariance] of two finite size populations of size `N` is given by

<!-- <equation class="equation" label="eq:population_covariance" align="center" raw="\operatorname{\mathrm{cov_N}} = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu_x)(y_i - \mu_y)" alt="Equation for the population covariance."> -->

```math
\mathop{\mathrm{cov_N}} = \frac{1}{N} \sum_{i=0}^{N-1} (x_i - \mu_x)(y_i - \mu_y)
```

<!-- </equation> -->

where the population means are given by

<!-- <equation class="equation" label="eq:population_mean_for_x" align="center" raw="\mu_x = \frac{1}{N} \sum_{i=0}^{N-1} x_i" alt="Equation for the population mean for first array."> -->

```math
\mu_x = \frac{1}{N} \sum_{i=0}^{N-1} x_i
```

<!-- </equation> -->

and

<!-- <equation class="equation" label="eq:population_mean_for_y" align="center" raw="\mu_y = \frac{1}{N} \sum_{i=0}^{N-1} y_i" alt="Equation for the population mean for second array."> -->

```math
\mu_y = \frac{1}{N} \sum_{i=0}^{N-1} y_i
```

<!-- </equation> -->

Often in the analysis of data, the true population [covariance][covariance] is not known _a priori_ and must be estimated from samples drawn from population distributions. If one attempts to use the formula for the population [covariance][covariance], the result is biased and yields a **biased sample covariance**. To compute an **unbiased sample covariance** for samples of size `n`,

<!-- <equation class="equation" label="eq:unbiased_sample_covariance" align="center" raw="\operatorname{\mathrm{cov_n}} = \frac{1}{n-1} \sum_{i=0}^{n-1} (x_i - \bar{x}_n)(y_i - \bar{y}_n)" alt="Equation for computing an unbiased sample variance."> -->

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

<!-- </equation> -->

where sample means are given by

<!-- <equation class="equation" label="eq:sample_mean_for_x" align="center" raw="\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i" alt="Equation for the sample mean for first array."> -->

```math
\bar{x} = \frac{1}{n} \sum_{i=0}^{n-1} x_i
```

<!-- </equation> -->

and

<!-- <equation class="equation" label="eq:sample_mean_for_y" align="center" raw="\bar{y} = \frac{1}{n} \sum_{i=0}^{n-1} y_i" alt="Equation for the sample mean for second array."> -->

```math
\bar{y} = \frac{1}{n} \sum_{i=0}^{n-1} y_i
```

<!-- </equation> -->

The use of the term `n-1` is commonly referred to as Bessel's correction. Depending on the characteristics of the population distributions, other correction factors (e.g., `n-1.5`, `n+1`, etc) can yield better estimators.

</section>

<!-- /.intro -->

<section class="usage">

## Usage

```javascript
var dcovarmtk = require( '@stdlib/stats/base/ndarray/dcovarmtk' );
```

#### dcovarmtk( arrays )

Computes the covariance of two one-dimensional double-precision floating-point ndarrays provided known means and using a one-pass textbook algorithm.

```javascript
var Float64Array = require( '@stdlib/array/float64' );
var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
var ndarray = require( '@stdlib/ndarray/base/ctor' );

var opts = {
'dtype': 'float64'
};

var xbuf = new Float64Array( [ 1.0, -2.0, 2.0 ] );
var x = new ndarray( opts.dtype, xbuf, [ 3 ], [ 1 ], 0, 'row-major' );

var ybuf = new Float64Array( [ 2.0, -2.0, 1.0 ] );
var y = new ndarray( opts.dtype, ybuf, [ 3 ], [ 1 ], 0, 'row-major' );

var meanx = scalar2ndarray( 1.0/3.0, opts );
var meany = scalar2ndarray( 1.0/3.0, opts );
var correction = scalar2ndarray( 1.0, opts );

var v = dcovarmtk( [ x, y, meanx, meany, correction ] );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@gururaj1512 Would you mind reordering the ndarrays here to

[ x, y, correction, meanx, meany ]

?

This ensures that the relative order of the ndarrays matches the order of the arguments in the corresponding strided array function

dcovarmtk( N, correction, meanx, x, strideX, meany, y, strideY )

Notice: correction, meanx, and meany order.

That applies throughout this PR.

// returns ~3.8333
```

The function has the following parameters:

- **arrays**: array-like object containing the following ndarrays in order:

1. first one-dimensional input ndarray.
2. second one-dimensional input ndarray.
3. a zero-dimensional ndarray specifying mean of the first one-dimensional ndarray.
4. a zero-dimensional ndarray specifying mean of the second one-dimensional ndarray.
5. a zero-dimensional ndarray specifying 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 [covariance][covariance] according to `N-c` where `c` corresponds to the provided degrees of freedom adjustment. When computing the population [covariance][covariance], setting this parameter to `0` is the standard choice (i.e., the provided arrays contain data constituting entire populations). When computing the unbiased sample [covariance][covariance], setting this parameter to `1` is the standard choice (i.e., the provided arrays contain data sampled from larger populations; this is commonly referred to as Bessel's correction).

</section>

<!-- /.usage -->

<section class="notes">

## Notes

- If provided an empty one-dimensional ndarray, the function returns `NaN`.

</section>

<!-- /.notes -->

<section class="examples">

## Examples

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

```javascript
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
var ndarray = require( '@stdlib/ndarray/base/ctor' );
var ndarray2array = require( '@stdlib/ndarray/to-array' );
var scalar2ndarray = require( '@stdlib/ndarray/from-scalar' );
var dcovarmtk = require( '@stdlib/stats/base/ndarray/dcovarmtk' );

// Define array options:
var opts = {
'dtype': 'float64'
};

// Create first one-dimensional ndarray containing pseudorandom integers drawn from a discrete uniform distribution:
var xbuf = discreteUniform( 10, -50, 50, opts );
var x = new ndarray( opts.dtype, xbuf, [ xbuf.length ], [ 1 ], 0, 'row-major' );
console.log( ndarray2array( x ) );

// Create second one-dimensional ndarray containing pseudorandom integers drawn from a discrete uniform distribution:
var ybuf = discreteUniform( 10, -50, 50, opts );
var y = new ndarray( opts.dtype, ybuf, [ ybuf.length ], [ 1 ], 0, 'row-major' );
console.log( ndarray2array( y ) );

// Specify the known means:
var meanx = scalar2ndarray( 0.0, opts );
var meany = scalar2ndarray( 0.0, opts );

// Specify the degrees of freedom adjustment:
var correction = scalar2ndarray( 1.0, opts );

// Calculate the sample covariance:
var v = dcovarmtk( [ x, y, meanx, meany, correction ] );
console.log( v );
```

</section>

<!-- /.examples -->

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

<section class="related">

</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">

</section>

<!-- /.links -->

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

</section>

<!-- /.links -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* @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 uniform = require( '@stdlib/random/array/uniform' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var ndarray = require( '@stdlib/ndarray/base/ctor' );
var scalar2ndarray = require( '@stdlib/ndarray/base/from-scalar' );
var pkg = require( './../package.json' ).name;
var dcovarmtk = require( './../lib' );


// VARIABLES //

var options = {
'dtype': 'float64'
};


// FUNCTIONS //

/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var correction;
var meanx;
var meany;
var xbuf;
var ybuf;
var x;
var y;

xbuf = uniform( len, -10.0, 10.0, options );
x = new ndarray( options.dtype, xbuf, [ len ], [ 1 ], 0, 'row-major' );

ybuf = uniform( len, -10.0, 10.0, options );
y = new ndarray( options.dtype, ybuf, [ len ], [ 1 ], 0, 'row-major' );

meanx = scalar2ndarray( 0.0, options.dtype, 'row-major' );
meany = scalar2ndarray( 0.0, options.dtype, 'row-major' );
correction = scalar2ndarray( 1.0, options.dtype, 'row-major' );

return benchmark;

function benchmark( b ) {
var v;
var i;

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = dcovarmtk( [ x, y, meanx, meany, correction ] );
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();
}
}


// MAIN //

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

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

for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+':len='+len, f );
}
}

main();
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@

{{alias}}( arrays )
Computes the covariance of two one-dimensional double-precision
floating-point ndarrays provided known means and using a one-pass textbook
algorithm.

If provided an empty ndarray, the function returns `NaN`.

Parameters
----------
arrays: ArrayLikeObject<ndarray>
The function expects the following ndarrays in order:

- first one-dimensional input ndarray.
- second one-dimensional input ndarray.
- a zero-dimensional ndarray specifying mean of the first
one-dimensional ndarray.
- a zero-dimensional ndarray specifying mean of the second
one-dimensional ndarray.
- a zero-dimensional ndarray specifying 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
covariance according to `N-c` where `c` corresponds to the provided
degrees of freedom adjustment. When computing the population
covariance, setting this parameter to `0` is the standard choice (i.e.,
the provided arrays contain data constituting entire populations). When
computing the unbiased sample covariance, setting this parameter to `1`
is the standard choice (i.e., the provided arrays contain data sampled
from larger populations; this is commonly referred to as Bessel's
correction).

Returns
-------
out: number
The covariance.

Examples
--------
// Create the input ndarrays:
> var xbuf = new {{alias:@stdlib/array/float64}}( [ 1.0, -2.0, 2.0 ] );
> var ybuf = new {{alias:@stdlib/array/float64}}( [ 2.0, -2.0, 1.0 ] );
> var dt = 'float64';
> var sh = [ xbuf.length ];
> var st = [ 1 ];
> var oo = 0;
> var ord = 'row-major';
> var x = new {{alias:@stdlib/ndarray/ctor}}( dt, xbuf, sh, st, oo, ord );
> var y = new {{alias:@stdlib/ndarray/ctor}}( dt, ybuf, sh, st, oo, ord );

// Specify the known means:
> var opts = { 'dtype': dt };
> var meanx = new {{alias:@stdlib/ndarray/from-scalar}}( 1.0/3.0, opts );
> var meany = new {{alias:@stdlib/ndarray/from-scalar}}( 1.0/3.0, opts );

// Specify the degrees of freedom adjustment:
> var correction = new {{alias:@stdlib/ndarray/from-scalar}}( 1.0, opts );

// Calculate the sample covariance:
> {{alias}}( [ x, y, meanx, meany, correction ] )
~3.8333

See Also
--------

Loading