Skip to content

Commit cf7c497

Browse files
committed
feat: add ndarray/to-array
This commit adds a utility to convert an ndarray to a list of nested arrays.
1 parent f546e24 commit cf7c497

File tree

11 files changed

+1152
-0
lines changed

11 files changed

+1152
-0
lines changed
Lines changed: 153 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
<!--
2+
3+
@license Apache-2.0
4+
5+
Copyright (c) 2023 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+
# ndarray2array
22+
23+
> Convert an [ndarray][@stdlib/ndarray/ctor] to a generic array.
24+
25+
<!-- Section to include introductory text. Make sure to keep an empty line after the intro `section` element and another before the `/section` close. -->
26+
27+
<section class="intro">
28+
29+
</section>
30+
31+
<!-- /.intro -->
32+
33+
<!-- Package usage documentation. -->
34+
35+
<section class="usage">
36+
37+
## Usage
38+
39+
```javascript
40+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
41+
```
42+
43+
#### ndarray2array( arr )
44+
45+
Converts an [ndarray][@stdlib/ndarray/ctor] to a generic array (which may include nested arrays).
46+
47+
```javascript
48+
var ndarray = require( '@stdlib/ndarray/ctor' );
49+
50+
var buffer = [ 1, 2, 3, 4 ];
51+
var shape = [ 2, 2 ];
52+
var order = 'row-major';
53+
var strides = [ 2, 1 ];
54+
var offset = 0;
55+
56+
var arr = ndarray( 'generic', buffer, shape, strides, offset, order );
57+
// returns <ndarray>
58+
59+
var out = ndarray2array( arr );
60+
// returns [ [ 1, 2 ], [ 3, 4 ] ]
61+
```
62+
63+
</section>
64+
65+
<!-- /.usage -->
66+
67+
<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
68+
69+
<section class="notes">
70+
71+
</section>
72+
73+
<!-- /.notes -->
74+
75+
<!-- Package usage examples. -->
76+
77+
<section class="examples">
78+
79+
## Examples
80+
81+
<!-- eslint no-undef: "error" -->
82+
83+
```javascript
84+
var shape2strides = require( '@stdlib/ndarray/base/shape2strides' );
85+
var strides2offset = require( '@stdlib/ndarray/base/strides2offset' );
86+
var discreteUniform = require( '@stdlib/random/base/discrete-uniform' );
87+
var zeroTo = require( '@stdlib/array/base/zero-to' );
88+
var ndarray = require( '@stdlib/ndarray/ctor' );
89+
var ndarray2array = require( '@stdlib/ndarray/to-array' );
90+
91+
// Create a data buffer:
92+
var buffer = zeroTo( 27 );
93+
94+
// Specify array meta data:
95+
var shape = [ 3, 3, 3 ];
96+
var order = 'column-major';
97+
var ndims = shape.length;
98+
99+
// Compute array meta data:
100+
var strides = shape2strides( shape, order );
101+
var offset = strides2offset( shape, strides );
102+
103+
// Print array information:
104+
console.log( '' );
105+
console.log( 'Dims: %s', shape.join( 'x' ) );
106+
107+
// Randomly flip strides and convert an ndarray to a nested array...
108+
var arr;
109+
var i;
110+
var j;
111+
for ( i = 0; i < 20; i++ ) {
112+
j = discreteUniform( 0, ndims-1 );
113+
strides[ j ] *= -1;
114+
offset = strides2offset( shape, strides );
115+
116+
console.log( '' );
117+
console.log( 'Strides: %s', strides.join( ',' ) );
118+
console.log( 'Offset: %d', offset );
119+
120+
arr = ndarray( 'generic', buffer, shape, strides, offset, order );
121+
console.log( JSON.stringify( ndarray2array( arr ) ) );
122+
}
123+
```
124+
125+
</section>
126+
127+
<!-- /.examples -->
128+
129+
<!-- Section to include cited references. If references are included, add a horizontal rule *before* the section. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
130+
131+
<section class="references">
132+
133+
</section>
134+
135+
<!-- /.references -->
136+
137+
<!-- Section for related `stdlib` packages. Do not manually edit this section, as it is automatically populated. -->
138+
139+
<section class="related">
140+
141+
</section>
142+
143+
<!-- /.related -->
144+
145+
<!-- Section for all links. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->
146+
147+
<section class="links">
148+
149+
[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib
150+
151+
</section>
152+
153+
<!-- /.links -->
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
/**
2+
* @license Apache-2.0
3+
*
4+
* Copyright (c) 2023 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 isArrayArray = require( '@stdlib/assert/is-array-array' );
25+
var shape2strides = require( '@stdlib/ndarray/base/shape2strides' );
26+
var strides2offset = require( '@stdlib/ndarray/base/strides2offset' );
27+
var numel = require( '@stdlib/ndarray/base/numel' );
28+
var zeroTo = require( '@stdlib/array/base/zero-to' );
29+
var ndarray = require( '@stdlib/ndarray/ctor' );
30+
var pkg = require( './../package.json' ).name;
31+
var ndarray2array = require( './../lib' );
32+
33+
34+
// MAIN //
35+
36+
bench( pkg+':order=row-major', function benchmark( b ) {
37+
var strides;
38+
var buffer;
39+
var offset;
40+
var order;
41+
var shape;
42+
var len;
43+
var arr;
44+
var out;
45+
var i;
46+
47+
shape = [ 10, 10, 10 ];
48+
order = 'row-major';
49+
len = numel( shape );
50+
buffer = zeroTo( len );
51+
strides = shape2strides( shape, order );
52+
offset = strides2offset( shape, strides );
53+
arr = ndarray( 'generic', buffer, shape, strides, offset, order );
54+
55+
b.tic();
56+
for ( i = 0; i < b.iterations; i++ ) {
57+
out = ndarray2array( arr );
58+
if ( out.length !== shape[ 0 ] ) {
59+
b.fail( 'should have expected length' );
60+
}
61+
}
62+
b.toc();
63+
if (
64+
!isArrayArray( out ) ||
65+
!isArrayArray( out[ 0 ] )
66+
) {
67+
b.fail( 'should return an array of arrays' );
68+
}
69+
b.pass( 'benchmark finished' );
70+
b.end();
71+
});
72+
73+
bench( pkg+':order=column-major', function benchmark( b ) {
74+
var strides;
75+
var buffer;
76+
var offset;
77+
var order;
78+
var shape;
79+
var len;
80+
var arr;
81+
var out;
82+
var i;
83+
84+
shape = [ 10, 10, 10 ];
85+
order = 'column-major';
86+
len = numel( shape );
87+
buffer = zeroTo( len );
88+
strides = shape2strides( shape, order );
89+
offset = strides2offset( shape, strides );
90+
arr = ndarray( 'generic', buffer, shape, strides, offset, order );
91+
92+
b.tic();
93+
for ( i = 0; i < b.iterations; i++ ) {
94+
out = ndarray2array( arr );
95+
if ( out.length !== shape[ 0 ] ) {
96+
b.fail( 'should have expected length' );
97+
}
98+
}
99+
b.toc();
100+
if (
101+
!isArrayArray( out ) ||
102+
!isArrayArray( out[ 0 ] )
103+
) {
104+
b.fail( 'should return an array of arrays' );
105+
}
106+
b.pass( 'benchmark finished' );
107+
b.end();
108+
});
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
#!/usr/bin/env python
2+
#
3+
# @license Apache-2.0
4+
#
5+
# Copyright (c) 2023 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+
"""Benchmark numpy.ndarray.tolist."""
20+
21+
from __future__ import print_function
22+
import timeit
23+
24+
NAME = "to-array"
25+
REPEATS = 3
26+
ITERATIONS = 10000
27+
COUNT = [0] # use a list to allow modification within nested scopes
28+
29+
30+
def print_version():
31+
"""Print the TAP version."""
32+
print("TAP version 13")
33+
34+
35+
def print_summary(total, passing):
36+
"""Print the benchmark summary.
37+
38+
# Arguments
39+
40+
* `total`: total number of tests
41+
* `passing`: number of passing tests
42+
43+
"""
44+
print("#")
45+
print("1.." + str(total)) # TAP plan
46+
print("# total " + str(total))
47+
print("# pass " + str(passing))
48+
print("#")
49+
print("# ok")
50+
51+
52+
def print_results(iterations, elapsed):
53+
"""Print benchmark results.
54+
55+
# Arguments
56+
57+
* `iterations`: number of iterations
58+
* `elapsed`: elapsed time (in seconds)
59+
60+
# Examples
61+
62+
``` python
63+
python> print_results(100000, 0.131009101868)
64+
```
65+
"""
66+
rate = iterations / elapsed
67+
68+
print(" ---")
69+
print(" iterations: " + str(iterations))
70+
print(" elapsed: " + str(elapsed))
71+
print(" rate: " + str(rate))
72+
print(" ...")
73+
74+
75+
def benchmark(name, setup, stmt, iterations):
76+
"""Run the benchmark and print benchmark results.
77+
78+
# Arguments
79+
80+
* `name`: benchmark name (suffix)
81+
* `setup`: benchmark setup
82+
* `stmt`: statement to benchmark
83+
* `iterations`: number of iterations
84+
85+
# Examples
86+
87+
``` python
88+
python> benchmark("::random", "from random import random;", "y = random()", 1000000)
89+
```
90+
"""
91+
t = timeit.Timer(stmt, setup=setup)
92+
93+
print_version()
94+
95+
i = 0
96+
while i < REPEATS:
97+
print("# python::numpy::" + NAME + name)
98+
COUNT[0] += 1
99+
elapsed = t.timeit(number=iterations)
100+
print_results(iterations, elapsed)
101+
print("ok " + str(COUNT[0]) + " benchmark finished")
102+
i += 1
103+
104+
105+
def main():
106+
"""Run the benchmarks."""
107+
name = ""
108+
setup = "import numpy as np; from random import random; x = np.zeros((10,10,10))"
109+
stmt = "y = x.tolist()"
110+
benchmark(name, setup, stmt, ITERATIONS)
111+
112+
print_summary(COUNT[0], COUNT[0])
113+
114+
115+
if __name__ == "__main__":
116+
main()

0 commit comments

Comments
 (0)