Skip to content

Commit 110f61c

Browse files
iampratik13kgryte
andauthored
feat: add stats/nanmidrange
PR-URL: #10076 Co-authored-by: Athan Reines <kgryte@gmail.com> Reviewed-by: Athan Reines <kgryte@gmail.com>
1 parent c73c8b3 commit 110f61c

13 files changed

Lines changed: 2762 additions & 0 deletions

File tree

Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2026 The Stdlib Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
19+
-->
20+
21+
# nanmidrange
22+
23+
> Compute the [**mid-range**][mid-range] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions, ignoring `NaN` values.
24+
25+
<section class="intro">
26+
27+
The [**mid-range**][mid-range], or **mid-extreme**, is the arithmetic mean of the maximum and minimum values in a data set. The measure is the midpoint of the range and a measure of central tendency.
28+
29+
</section>
30+
31+
<!-- /.intro -->
32+
33+
<section class="usage">
34+
35+
## Usage
36+
37+
```javascript
38+
var nanmidrange = require( '@stdlib/stats/nanmidrange' );
39+
```
40+
41+
#### nanmidrange( x\[, options] )
42+
43+
Computes the [**mid-range**][mid-range] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions, ignoring `NaN` values.
44+
45+
```javascript
46+
var array = require( '@stdlib/ndarray/array' );
47+
48+
var x = array( [ -1.0, 2.0, NaN ] );
49+
50+
var y = nanmidrange( x );
51+
// returns <ndarray>[ 0.5 ]
52+
```
53+
54+
The function has the following parameters:
55+
56+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
57+
- **options**: function options (_optional_).
58+
59+
The function accepts the following options:
60+
61+
- **dims**: list of dimensions over which to perform a reduction. If not provided, the function performs a reduction over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
62+
- **dtype**: output ndarray [data type][@stdlib/ndarray/dtypes]. Must be a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
63+
- **keepdims**: boolean indicating whether the reduced dimensions should be included in the returned [ndarray][@stdlib/ndarray/ctor] as singleton dimensions. Default: `false`.
64+
65+
By default, the function performs a reduction over all elements in a provided input [ndarray][@stdlib/ndarray/ctor]. To perform a reduction over specific dimensions, provide a `dims` option.
66+
67+
```javascript
68+
var array = require( '@stdlib/ndarray/array' );
69+
70+
var x = array( [ -1.0, 2.0, NaN, 4.0 ], {
71+
'shape': [ 2, 2 ],
72+
'order': 'row-major'
73+
});
74+
// returns <ndarray>[ [ -1.0, 2.0 ], [ NaN, 4.0 ] ]
75+
76+
var y = nanmidrange( x, {
77+
'dims': [ 0 ]
78+
});
79+
// returns <ndarray>[ -1.0, 3.0 ]
80+
81+
y = nanmidrange( x, {
82+
'dims': [ 1 ]
83+
});
84+
// returns <ndarray>[ 0.5, 4.0 ]
85+
86+
y = nanmidrange( x, {
87+
'dims': [ 0, 1 ]
88+
});
89+
// returns <ndarray>[ 1.5 ]
90+
```
91+
92+
By default, the function excludes reduced dimensions from the output [ndarray][@stdlib/ndarray/ctor]. To include the reduced dimensions as singleton dimensions, set the `keepdims` option to `true`.
93+
94+
```javascript
95+
var array = require( '@stdlib/ndarray/array' );
96+
97+
var x = array( [ -1.0, 2.0, NaN, 4.0 ], {
98+
'shape': [ 2, 2 ],
99+
'order': 'row-major'
100+
});
101+
// returns <ndarray>[ [ -1.0, 2.0 ], [ NaN, 4.0 ] ]
102+
103+
var y = nanmidrange( x, {
104+
'dims': [ 0 ],
105+
'keepdims': true
106+
});
107+
// returns <ndarray>[ [ -1.0, 3.0 ] ]
108+
109+
y = nanmidrange( x, {
110+
'dims': [ 1 ],
111+
'keepdims': true
112+
});
113+
// returns <ndarray>[ [ 0.5 ], [ 4.0 ] ]
114+
115+
y = nanmidrange( x, {
116+
'dims': [ 0, 1 ],
117+
'keepdims': true
118+
});
119+
// returns <ndarray>[ [ 1.5 ] ]
120+
```
121+
122+
By default, the function returns an [ndarray][@stdlib/ndarray/ctor] having a [data type][@stdlib/ndarray/dtypes] determined by the function's output data type [policy][@stdlib/ndarray/output-dtype-policies]. To override the default behavior, set the `dtype` option.
123+
124+
```javascript
125+
var getDType = require( '@stdlib/ndarray/dtype' );
126+
var array = require( '@stdlib/ndarray/array' );
127+
128+
var x = array( [ -1.0, 2.0, NaN ], {
129+
'dtype': 'generic'
130+
});
131+
132+
var y = nanmidrange( x, {
133+
'dtype': 'float64'
134+
});
135+
// returns <ndarray>[ 0.5 ]
136+
137+
var dt = String( getDType( y ) );
138+
// returns 'float64'
139+
```
140+
141+
#### nanmidrange.assign( x, out\[, options] )
142+
143+
Computes the [**mid-range**][mid-range] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions, ignoring `NaN` values, and assigns results to a provided output [ndarray][@stdlib/ndarray/ctor].
144+
145+
```javascript
146+
var array = require( '@stdlib/ndarray/array' );
147+
var zeros = require( '@stdlib/ndarray/zeros' );
148+
149+
var x = array( [ -1.0, 2.0, NaN ] );
150+
var y = zeros( [] );
151+
152+
var out = nanmidrange.assign( x, y );
153+
// returns <ndarray>[ 0.5 ]
154+
155+
var bool = ( out === y );
156+
// returns true
157+
```
158+
159+
The method has the following parameters:
160+
161+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
162+
- **out**: output [ndarray][@stdlib/ndarray/ctor].
163+
- **options**: function options (_optional_).
164+
165+
The method accepts the following options:
166+
167+
- **dims**: list of dimensions over which to perform a reduction. If not provided, the function performs a reduction over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
168+
169+
</section>
170+
171+
<!-- /.usage -->
172+
173+
<section class="notes">
174+
175+
## Notes
176+
177+
- Setting the `keepdims` option to `true` can be useful when wanting to ensure that the output [ndarray][@stdlib/ndarray/ctor] is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with ndarrays having the same shape as the input [ndarray][@stdlib/ndarray/ctor].
178+
- The output data type [policy][@stdlib/ndarray/output-dtype-policies] only applies to the main function and specifies that, by default, the function must return an [ndarray][@stdlib/ndarray/ctor] having the same [data type][@stdlib/ndarray/dtypes] as the input [ndarray][@stdlib/ndarray/ctor]. For the `assign` method, the output [ndarray][@stdlib/ndarray/ctor] is allowed to have any supported output [data type][@stdlib/ndarray/dtypes].
179+
180+
</section>
181+
182+
<!-- /.notes -->
183+
184+
<section class="examples">
185+
186+
## Examples
187+
188+
<!-- eslint no-undef: "error" -->
189+
190+
```javascript
191+
var uniform = require( '@stdlib/random/base/uniform' );
192+
var filledarrayBy = require( '@stdlib/array/filled-by' );
193+
var bernoulli = require( '@stdlib/random/base/bernoulli' );
194+
var getDType = require( '@stdlib/ndarray/dtype' );
195+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
196+
var ndarray = require( '@stdlib/ndarray/ctor' );
197+
var nanmidrange = require( '@stdlib/stats/nanmidrange' );
198+
199+
function rand() {
200+
if ( bernoulli( 0.8 ) < 1 ) {
201+
return NaN;
202+
}
203+
return uniform( -50.0, 50.0 );
204+
}
205+
206+
// Generate an array of random numbers:
207+
var xbuf = filledarrayBy( 25, 'generic', rand );
208+
209+
// Wrap in an ndarray:
210+
var x = new ndarray( 'generic', xbuf, [ 5, 5 ], [ 5, 1 ], 0, 'row-major' );
211+
console.log( ndarray2array( x ) );
212+
213+
// Perform a reduction:
214+
var y = nanmidrange( x, {
215+
'dims': [ 0 ]
216+
});
217+
218+
// Resolve the output array data type:
219+
var dt = getDType( y );
220+
console.log( dt );
221+
222+
// Print the results:
223+
console.log( ndarray2array( y ) );
224+
```
225+
226+
</section>
227+
228+
<!-- /.examples -->
229+
230+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
231+
232+
<section class="related">
233+
234+
</section>
235+
236+
<!-- /.related -->
237+
238+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
239+
240+
<section class="links">
241+
242+
[mid-range]: https://en.wikipedia.org/wiki/Mid-range
243+
244+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
245+
246+
[@stdlib/ndarray/dtypes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/dtypes
247+
248+
[@stdlib/ndarray/output-dtype-policies]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/output-dtype-policies
249+
250+
[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes
251+
252+
</section>
253+
254+
<!-- /.links -->
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2026 The Stdlib Authors.
5+
*
6+
* Licensed under the Apache License, Version 2.0 (the "License");
7+
* you may not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing, software
13+
* distributed under the License is distributed on an "AS IS" BASIS,
14+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*/
18+
19+
'use strict';
20+
21+
// MODULES //
22+
23+
var bench = require( '@stdlib/bench' );
24+
var isnan = require( '@stdlib/math/base/assert/is-nan' );
25+
var pow = require( '@stdlib/math/base/special/pow' );
26+
var uniform = require( '@stdlib/random/base/uniform' );
27+
var bernoulli = require( '@stdlib/random/base/bernoulli' );
28+
var filledarrayBy = require( '@stdlib/array/filled-by' );
29+
var zeros = require( '@stdlib/array/zeros' );
30+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
31+
var format = require( '@stdlib/string/format' );
32+
var pkg = require( './../package.json' ).name;
33+
var nanmidrange = require( './../lib' );
34+
35+
36+
// VARIABLES //
37+
38+
var options = {
39+
'dtype': 'float64'
40+
};
41+
42+
43+
// FUNCTIONS //
44+
45+
/**
46+
* Returns a random number.
47+
*
48+
* @private
49+
* @returns {number} random number
50+
*/
51+
function rand() {
52+
if ( bernoulli( 0.8 ) < 1 ) {
53+
return NaN;
54+
}
55+
return uniform( -10.0, 10.0 );
56+
}
57+
58+
/**
59+
* Creates a benchmark function.
60+
*
61+
* @private
62+
* @param {PositiveInteger} len - array length
63+
* @returns {Function} benchmark function
64+
*/
65+
function createBenchmark( len ) {
66+
var out;
67+
var x;
68+
69+
x = filledarrayBy( len, options.dtype, rand );
70+
x = new ndarray( options.dtype, x, [ len ], [ 1 ], 0, 'row-major' );
71+
72+
out = new ndarray( options.dtype, zeros( 1, options.dtype ), [], [ 0 ], 0, 'row-major' );
73+
74+
return benchmark;
75+
76+
/**
77+
* Benchmark function.
78+
*
79+
* @private
80+
* @param {Benchmark} b - benchmark instance
81+
*/
82+
function benchmark( b ) {
83+
var o;
84+
var i;
85+
86+
b.tic();
87+
for ( i = 0; i < b.iterations; i++ ) {
88+
o = nanmidrange.assign( x, out );
89+
if ( typeof o !== 'object' ) {
90+
b.fail( 'should return an ndarray' );
91+
}
92+
}
93+
b.toc();
94+
if ( isnan( o.get() ) ) {
95+
b.fail( 'should not return NaN' );
96+
}
97+
b.pass( 'benchmark finished' );
98+
b.end();
99+
}
100+
}
101+
102+
103+
// MAIN //
104+
105+
/**
106+
* Main execution sequence.
107+
*
108+
* @private
109+
*/
110+
function main() {
111+
var len;
112+
var min;
113+
var max;
114+
var f;
115+
var i;
116+
117+
min = 1; // 10^min
118+
max = 6; // 10^max
119+
120+
for ( i = min; i <= max; i++ ) {
121+
len = pow( 10, i );
122+
f = createBenchmark( len );
123+
bench( format( '%s:assign:dtype=%s,len=%d', pkg, options.dtype, len ), f );
124+
}
125+
}
126+
127+
main();

0 commit comments

Comments
 (0)