Skip to content

Commit 93a6944

Browse files
headlessNodekgrytestdlib-bot
authored andcommitted
feat: add blas/ext/to-sortedhp
PR-URL: stdlib-js#8182 Closes: stdlib-js/metr-issue-tracker#100 Ref: stdlib-js#2656 Co-authored-by: Athan Reines <[email protected]> Reviewed-by: Athan Reines <[email protected]> Co-authored-by: stdlib-bot <[email protected]>
1 parent 3a25df5 commit 93a6944

File tree

14 files changed

+5519
-0
lines changed

14 files changed

+5519
-0
lines changed
Lines changed: 245 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,245 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2025 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+
# toSortedhp
22+
23+
> Return a new [ndarray][@stdlib/ndarray/ctor] containing the elements of an input [ndarray][@stdlib/ndarray/ctor] sorted along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using heapsort.
24+
25+
<section class="usage">
26+
27+
## Usage
28+
29+
```javascript
30+
var toSortedhp = require( '@stdlib/blas/ext/to-sortedhp' );
31+
```
32+
33+
#### toSortedhp( x\[, sortOrder]\[, options] )
34+
35+
Returns a new [ndarray][@stdlib/ndarray/ctor] containing the elements of an input [ndarray][@stdlib/ndarray/ctor] sorted along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using heapsort.
36+
37+
```javascript
38+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
39+
var array = require( '@stdlib/ndarray/array' );
40+
41+
var x = array( [ -1.0, 2.0, -3.0 ] );
42+
43+
var y = toSortedhp( x );
44+
// returns <ndarray>
45+
46+
var arr = ndarray2array( y );
47+
// returns [ -3.0, -1.0, 2.0 ]
48+
```
49+
50+
The function has the following parameters:
51+
52+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
53+
- **sortOrder**: sort order (_optional_). May be either a scalar value, string, or an [ndarray][@stdlib/ndarray/ctor] having a real-valued or "generic" [data type][@stdlib/ndarray/dtypes]. If provided an [ndarray][@stdlib/ndarray/ctor], the value must have a shape which is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with the complement of the shape defined by `options.dims`. For example, given the input shape `[2, 3, 4]` and `options.dims=[0]`, an [ndarray][@stdlib/ndarray/ctor] sort order must have a shape which is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with the shape `[3, 4]`. Similarly, when performing the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor], an [ndarray][@stdlib/ndarray/ctor] sort order must be a zero-dimensional [ndarray][@stdlib/ndarray/ctor]. By default, the sort order is `1` (i.e., increasing order).
54+
- **options**: function options (_optional_).
55+
56+
The function accepts the following options:
57+
58+
- **dims**: list of dimensions over which to perform operation. If not provided, the function performs the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
59+
- **dtype**: output [ndarray][@stdlib/ndarray/ctor] [data type][@stdlib/ndarray/dtypes].
60+
61+
By default, the function sorts elements in increasing order. To sort in a different order, provide a `sortOrder` argument.
62+
63+
```javascript
64+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
65+
var array = require( '@stdlib/ndarray/array' );
66+
67+
var x = array( [ -1.0, 2.0, -3.0 ] );
68+
69+
var y = toSortedhp( x, -1.0 );
70+
// returns <ndarray>
71+
72+
var arr = ndarray2array( y );
73+
// returns [ 2.0, -1.0, -3.0 ]
74+
```
75+
76+
In addition to numeric values, one can specify the sort order via one of the following string literals: `'ascending'`, `'asc'`, `'descending'`, or `'desc'`. The first two literals indicate to sort in ascending (i.e., increasing) order. The last two literals indicate to sort in descending (i.e., decreasing) order.
77+
78+
```javascript
79+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
80+
var array = require( '@stdlib/ndarray/array' );
81+
82+
var x = array( [ -1.0, 2.0, -3.0 ] );
83+
84+
// Sort in ascending order:
85+
var y = toSortedhp( x, 'asc' );
86+
// returns <ndarray>
87+
88+
var arr = ndarray2array( y );
89+
// returns [ -3.0, -1.0, 2.0 ]
90+
91+
// Sort in descending order:
92+
y = toSortedhp( x, 'descending' );
93+
// returns <ndarray>
94+
95+
arr = ndarray2array( y );
96+
// returns [ 2.0, -1.0, -3.0 ]
97+
```
98+
99+
By default, the function performs the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor]. To perform the operation over specific dimensions, provide a `dims` option.
100+
101+
```javascript
102+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
103+
var array = require( '@stdlib/ndarray/array' );
104+
105+
var x = array( [ -1.0, 2.0, -3.0, 4.0 ], {
106+
'shape': [ 2, 2 ],
107+
'order': 'row-major'
108+
});
109+
110+
var v = ndarray2array( x );
111+
// returns [ [ -1.0, 2.0 ], [ -3.0, 4.0 ] ]
112+
113+
var y = toSortedhp( x, {
114+
'dims': [ 0 ]
115+
});
116+
// returns <ndarray>
117+
118+
v = ndarray2array( y );
119+
// returns [ [ -3.0, 2.0 ], [ -1.0, 4.0 ] ]
120+
```
121+
122+
To specify the output [ndarray][@stdlib/ndarray/ctor] [data type][@stdlib/ndarray/dtypes], provide a `dtype` option.
123+
124+
```javascript
125+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
126+
var array = require( '@stdlib/ndarray/array' );
127+
128+
var x = array( [ -1.0, 2.0, -3.0 ] );
129+
130+
var y = toSortedhp( x, {
131+
'dtype': 'float32'
132+
});
133+
// returns <ndarray>
134+
135+
var arr = ndarray2array( y );
136+
// returns [ -3.0, -1.0, 2.0 ]
137+
```
138+
139+
#### toSortedhp.assign( x, out\[, sortOrder]\[, options] )
140+
141+
Sorts the elements of an input [ndarray][@stdlib/ndarray/ctor] along one or more [ndarray][@stdlib/ndarray/ctor] dimensions using heapsort and assigns the results to an output [ndarray][@stdlib/ndarray/ctor].
142+
143+
```javascript
144+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
145+
var zeros = require( '@stdlib/ndarray/zeros' );
146+
var array = require( '@stdlib/ndarray/array' );
147+
148+
var x = array( [ -1.0, 2.0, -3.0 ] );
149+
var y = zeros( [ 3 ] );
150+
151+
var out = toSortedhp.assign( x, y );
152+
// returns <ndarray>
153+
154+
var arr = ndarray2array( out );
155+
// returns [ -3.0, -1.0, 2.0 ]
156+
157+
var bool = ( y === out );
158+
// returns true
159+
```
160+
161+
The function has the following parameters:
162+
163+
- **x**: input [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
164+
- **out**: output [ndarray][@stdlib/ndarray/ctor]. Must have a real-valued or "generic" [data type][@stdlib/ndarray/dtypes].
165+
- **sortOrder**: sort order (_optional_). May be either a scalar value, string, or an [ndarray][@stdlib/ndarray/ctor] having a real-valued or "generic" [data type][@stdlib/ndarray/dtypes]. If provided an [ndarray][@stdlib/ndarray/ctor], the value must have a shape which is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with the complement of the shape defined by `options.dims`. For example, given the input shape `[2, 3, 4]` and `options.dims=[0]`, an [ndarray][@stdlib/ndarray/ctor] sort order must have a shape which is [broadcast-compatible][@stdlib/ndarray/base/broadcast-shapes] with the shape `[3, 4]`. Similarly, when performing the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor], an [ndarray][@stdlib/ndarray/ctor] sort order must be a zero-dimensional [ndarray][@stdlib/ndarray/ctor]. By default, the sort order is `1` (i.e., increasing order).
166+
- **options**: function options (_optional_).
167+
168+
The function accepts the following options:
169+
170+
- **dims**: list of dimensions over which to perform operation. If not provided, the function performs the operation over all elements in a provided input [ndarray][@stdlib/ndarray/ctor].
171+
172+
</section>
173+
174+
<!-- /.usage -->
175+
176+
<section class="notes">
177+
178+
## Notes
179+
180+
- If `sortOrder < 0.0` or is either `'desc'` or `'descending'`, the input [ndarray][@stdlib/ndarray/ctor] is sorted in **decreasing** order. If `sortOrder > 0.0` or is either `'asc'` or `'ascending'`, the input [ndarray][@stdlib/ndarray/ctor] is sorted in **increasing** order. If `sortOrder == 0.0`, the input [ndarray][@stdlib/ndarray/ctor] is left unchanged.
181+
- The algorithm distinguishes between `-0` and `+0`. When sorted in increasing order, `-0` is sorted before `+0`. When sorted in decreasing order, `-0` is sorted after `+0`.
182+
- The algorithm sorts `NaN` values to the end. When sorted in increasing order, `NaN` values are sorted last. When sorted in decreasing order, `NaN` values are sorted first.
183+
- The algorithm has space complexity `O(1)` and time complexity `O(N log2 N)`.
184+
- The algorithm is **unstable**, meaning that the algorithm may change the order of [ndarray][@stdlib/ndarray/ctor] elements which are equal or equivalent (e.g., `NaN` values).
185+
- The function iterates over [ndarray][@stdlib/ndarray/ctor] elements according to the memory layout of the input [ndarray][@stdlib/ndarray/ctor]. Accordingly, performance degradation is possible when operating over multiple dimensions of a large non-contiguous multi-dimensional input [ndarray][@stdlib/ndarray/ctor]. In such scenarios, one may want to copy an input [ndarray][@stdlib/ndarray/ctor] to contiguous memory before sorting.
186+
187+
</section>
188+
189+
<!-- /.notes -->
190+
191+
<section class="examples">
192+
193+
## Examples
194+
195+
<!-- eslint no-undef: "error" -->
196+
197+
```javascript
198+
var discreteUniform = require( '@stdlib/random/array/discrete-uniform' );
199+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
200+
var ndarray = require( '@stdlib/ndarray/ctor' );
201+
var toSortedhp = require( '@stdlib/blas/ext/to-sortedhp' );
202+
203+
// Generate an array of random numbers:
204+
var xbuf = discreteUniform( 25, -20, 20, {
205+
'dtype': 'generic'
206+
});
207+
208+
// Wrap in an ndarray:
209+
var x = new ndarray( 'generic', xbuf, [ 5, 5 ], [ 5, 1 ], 0, 'row-major' );
210+
console.log( ndarray2array( x ) );
211+
212+
// Perform operation:
213+
var out = toSortedhp( x, {
214+
'dims': [ 0 ]
215+
});
216+
217+
// Print the results:
218+
console.log( ndarray2array( out ) );
219+
```
220+
221+
</section>
222+
223+
<!-- /.examples -->
224+
225+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
226+
227+
<section class="related">
228+
229+
</section>
230+
231+
<!-- /.related -->
232+
233+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
234+
235+
<section class="links">
236+
237+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor
238+
239+
[@stdlib/ndarray/dtypes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/dtypes
240+
241+
[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes
242+
243+
</section>
244+
245+
<!-- /.links -->
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2025 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/array/uniform' );
27+
var ndarray = require( '@stdlib/ndarray/base/ctor' );
28+
var zeros = require( '@stdlib/ndarray/zeros' );
29+
var pkg = require( './../package.json' ).name;
30+
var assign = require( './../lib/assign.js' );
31+
32+
33+
// VARIABLES //
34+
35+
var options = {
36+
'dtype': 'float64'
37+
};
38+
39+
40+
// FUNCTIONS //
41+
42+
/**
43+
* Creates a benchmark function.
44+
*
45+
* @private
46+
* @param {PositiveInteger} len - array length
47+
* @returns {Function} benchmark function
48+
*/
49+
function createBenchmark( len ) {
50+
var x;
51+
var y;
52+
53+
x = uniform( len, -50.0, 50.0, options );
54+
x = new ndarray( options.dtype, x, [ len ], [ 1 ], 0, 'row-major' );
55+
y = zeros( [ len ], {
56+
'dtype': options.dtype
57+
});
58+
59+
return benchmark;
60+
61+
/**
62+
* Benchmark function.
63+
*
64+
* @private
65+
* @param {Benchmark} b - benchmark instance
66+
*/
67+
function benchmark( b ) {
68+
var o;
69+
var i;
70+
71+
b.tic();
72+
for ( i = 0; i < b.iterations; i++ ) {
73+
o = assign( x, y, ( i%2 ) ? 1 : -1 );
74+
if ( typeof o !== 'object' ) {
75+
b.fail( 'should return an ndarray' );
76+
}
77+
}
78+
b.toc();
79+
if ( isnan( y.get( i%len ) ) ) {
80+
b.fail( 'should not return NaN' );
81+
}
82+
b.pass( 'benchmark finished' );
83+
b.end();
84+
}
85+
}
86+
87+
88+
// MAIN //
89+
90+
/**
91+
* Main execution sequence.
92+
*
93+
* @private
94+
*/
95+
function main() {
96+
var len;
97+
var min;
98+
var max;
99+
var f;
100+
var i;
101+
102+
min = 1; // 10^min
103+
max = 6; // 10^max
104+
105+
for ( i = min; i <= max; i++ ) {
106+
len = pow( 10, i );
107+
f = createBenchmark( len );
108+
bench( pkg+':assign:dtype='+options.dtype+',len='+len, f );
109+
}
110+
}
111+
112+
main();

0 commit comments

Comments
 (0)