Skip to content

feat: add ndarray/base/broadcast-array-except-dimensions #7853

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 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<!--

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

-->

# broadcastArrayExceptDimensions

> Broadcast an input [ndarray][@stdlib/ndarray/base/ctor] to a target shape keeping the specified dimensions unchanged.

<!-- Section to include introductory text. Make sure to keep an empty line after the intro `section` element and another before the `/section` close. -->

<section class="intro">

</section>

<!-- /.intro -->

<!-- Package usage documentation. -->

<section class="usage">

## Usage

<!-- eslint-disable id-length -->

```javascript
var broadcastArrayExceptDimensions = require( '@stdlib/ndarray/base/broadcast-array-except-dimensions' );
```

#### broadcastArrayExceptDimensions( arr, shape\[, dims] )

Broadcast an input [ndarray][@stdlib/ndarray/base/ctor] to a target shape keeping the specified dimensions unchanged.

```javascript
var array = require( '@stdlib/ndarray/array' );

// Create a 2x2 ndarray:
var x = array( [ [ 1, 2 ], [ 3, 4 ] ] );
// returns <ndarray>

// Perform broadcasting:
var y = broadcastArrayExceptDimensions( x, [ 3, 2, 2 ] );
// returns <ndarray>

var ysh = y.shape;
// returns [ 3, 2, 2 ]
```

The function accepts the following arguments:

- **arr**: input ndarray.
- **shape**: target shape.
- **dims**: list of dimensions which are exculded from broadcasting. Default: `[ -1 ]` (_optional_).

To exclude specific dimensions from broadcasting, provide a `dims` parameter.

```javascript
var array = require( '@stdlib/ndarray/array' );

// Create a 2x2 ndarray:
var x = array( [ [ 1, 2 ], [ 3, 4 ] ] );
// returns <ndarray>

// Perform broadcasting:
var y = broadcastArrayExceptDimensions( x, [ 3, 2, 2 ], [ -2 ] );
// returns <ndarray>

var ysh = y.shape;
// returns [ 3, 2, 2 ]
```

</section>

<!-- /.usage -->

<!-- Package usage notes. Make sure to keep an empty line after the `section` element and another before the `/section` close. -->

<section class="notes">

## Notes

- The function throws an error if a provided [ndarray][@stdlib/ndarray/base/ctor] is [incompatible][@stdlib/ndarray/base/broadcast-shapes] with a provided shape.
- The returned [ndarray][@stdlib/ndarray/base/ctor] is a "base" [ndarray][@stdlib/ndarray/base/ctor], and, thus, the returned [ndarray][@stdlib/ndarray/base/ctor] does not perform bounds checking or afford any of the guarantees of the non-base [ndarray][@stdlib/ndarray/ctor] constructor. The primary intent of this function is to broadcast an ndarray-like object within internal implementations and to do so with minimal overhead.
- The function always returns a new [ndarray][@stdlib/ndarray/base/ctor] instance even if the input [ndarray][@stdlib/ndarray/base/ctor] shape and the desired shape are the same.

</section>

<!-- /.notes -->

<!-- Package usage examples. -->

<section class="examples">

## Examples

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

```javascript
var array = require( '@stdlib/ndarray/array' );
var numel = require( '@stdlib/ndarray/base/numel' );
var ind2sub = require( '@stdlib/ndarray/ind2sub' );
var broadcastArrayExceptDimensions = require( '@stdlib/ndarray/base/broadcast-array-except-dimensions' );

// Create a 1x3 array:
var x = array( [ [ 1, 2, 3 ] ] );
// returns <ndarray>

// Broadcast the array to 3x2x2:
var y = broadcastArrayExceptDimensions( x, [ 2, 2, 3 ], [ -2 ] );
// returns <ndarray>

// Retrieve the shape:
var sh = y.shape;
// returns [ 2, 1, 3 ]

// Retrieve the number of elements:
var N = numel( sh );

// Loop through the array elements...
var sub;
var v;
var i;
for ( i = 0; i < N; i++ ) {
v = y.iget( i );
sub = ind2sub( sh, i );
console.log( 'Y[%s] = %d', sub.join( ', ' ), v );
}
```

</section>

<!-- /.examples -->

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

<section class="references">

</section>

<!-- /.references -->

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

[@stdlib/ndarray/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/ctor

[@stdlib/ndarray/base/ctor]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/ctor

[@stdlib/ndarray/base/broadcast-shapes]: https://github.com/stdlib-js/stdlib/tree/develop/lib/node_modules/%40stdlib/ndarray/base/broadcast-shapes

</section>

<!-- /.links -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/**
* @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 Float64Array = require( '@stdlib/array/float64' );
var ndarrayBase = require( '@stdlib/ndarray/base/ctor' );
var ndarray = require( '@stdlib/ndarray/ctor' );
var isndarrayLike = require( '@stdlib/assert/is-ndarray-like' );
var pkg = require( './../package.json' ).name;
var broadcastArrayExceptDimensions = require( './../lib' );

Check warning on line 29 in lib/node_modules/@stdlib/ndarray/base/broadcast-array-except-dimensions/benchmark/benchmark.js

View workflow job for this annotation

GitHub Actions / Lint Changed Files

Identifier name 'broadcastArrayExceptDimensions' is too long (> 25)


// MAIN //

bench( pkg+'::base_ndarray,2d', function benchmark( b ) {
var strides;
var values;
var buffer;
var offset;
var dtype;
var shape;
var order;
var out;
var i;

dtype = 'float64';
buffer = new Float64Array( 4 );
shape = [ 2, 2 ];
strides = [ 2, 1 ];
offset = 0;
order = 'row-major';

values = [
ndarrayBase( dtype, buffer, shape, strides, offset, order ),
ndarrayBase( dtype, buffer, shape, strides, offset, order ),
ndarrayBase( dtype, buffer, shape, strides, offset, order ),
ndarrayBase( dtype, buffer, shape, strides, offset, order ),
ndarrayBase( dtype, buffer, shape, strides, offset, order )
];

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = broadcastArrayExceptDimensions( values[ i%values.length ], [ 2, 2, 2 ] );

Check warning on line 62 in lib/node_modules/@stdlib/ndarray/base/broadcast-array-except-dimensions/benchmark/benchmark.js

View workflow job for this annotation

GitHub Actions / Lint Changed Files

This line has a length of 87. Maximum allowed is 80
if ( typeof out !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !isndarrayLike( out ) ) {
b.fail( 'should return an ndarray' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( pkg+'::ndarray,2d', function benchmark( b ) {
var strides;
var values;
var buffer;
var offset;
var dtype;
var shape;
var order;
var out;
var i;

dtype = 'float64';
buffer = new Float64Array( 4 );
shape = [ 2, 2 ];
strides = [ 2, 1 ];
offset = 0;
order = 'row-major';

values = [
ndarray( dtype, buffer, shape, strides, offset, order ),
ndarray( dtype, buffer, shape, strides, offset, order ),
ndarray( dtype, buffer, shape, strides, offset, order ),
ndarray( dtype, buffer, shape, strides, offset, order ),
ndarray( dtype, buffer, shape, strides, offset, order )
];

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = broadcastArrayExceptDimensions( values[ i%values.length ], [ 2, 2, 2 ] );

Check warning on line 103 in lib/node_modules/@stdlib/ndarray/base/broadcast-array-except-dimensions/benchmark/benchmark.js

View workflow job for this annotation

GitHub Actions / Lint Changed Files

This line has a length of 87. Maximum allowed is 80
if ( typeof out !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !isndarrayLike( out ) ) {
b.fail( 'should return an ndarray' );
}
b.pass( 'benchmark finished' );
b.end();
});

bench( pkg+'::ndarray_like,2d', function benchmark( b ) {
var strides;
var values;
var buffer;
var offset;
var dtype;
var shape;
var order;
var out;
var obj;
var i;

dtype = 'float64';
buffer = new Float64Array( 4 );
shape = [ 2, 2 ];
strides = [ 2, 1 ];
offset = 0;
order = 'row-major';

values = [];
for ( i = 0; i < 5; i++ ) {
obj = {
'dtype': dtype,
'data': buffer,
'shape': shape,
'strides': strides,
'offset': offset,
'order': order
};
values.push( obj );
}

b.tic();
for ( i = 0; i < b.iterations; i++ ) {
out = broadcastArrayExceptDimensions( values[ i%values.length ], [ 2, 2, 2 ] );

Check warning on line 150 in lib/node_modules/@stdlib/ndarray/base/broadcast-array-except-dimensions/benchmark/benchmark.js

View workflow job for this annotation

GitHub Actions / Lint Changed Files

This line has a length of 87. Maximum allowed is 80
if ( typeof out !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( !isndarrayLike( out ) ) {
b.fail( 'should return an ndarray' );
}
b.pass( 'benchmark finished' );
b.end();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@

{{alias}}( arr, shape[, dims] )
Broadcasts an input ndarray to a target shape keeping the specified
dimensions unchanged.

The returned array is a "base" ndarray, and, thus, the returned array does
not perform bounds checking or afford any of the guarantees of the non-base
ndarray constructor. The primary intent of this function is to broadcast an
ndarray-like object within internal implementations and to do so with
minimal overhead.

The function always returns a new ndarray instance even if the input ndarray
shape and the desired shape are the same.

The function throws an error if a provided ndarray is incompatible with a
provided shape.

Parameters
----------
arr: ndarray
Input array.

shape: ArrayLikeObject
Desired shape.

dims: Array<integer> (optional)
List of dimensions to exclude from broadcasting.

Returns
-------
out: ndarray
Broadcasted array.

Examples
--------
> var x = {{alias:@stdlib/ndarray/array}}( [ [ 1, 2, 3 ] ] )
<ndarray>
> var sh = x.shape
[ 1, 3 ]
> var y = {{alias}}( x, [ 2, 2, 3 ], [ -2 ] )
<ndarray>
> sh = y.shape
[ 2, 1, 3 ]
> var v = y.get( 0, 0, 0 )
1
> v = y.get( 0, 0, 1 )
2
> v = y.get( 0, 0, 2 )
3
> v = y.get( 1, 0, 0 )
1
> v = y.get( 1, 0, 1 )
2
> v = y.get( 1, 0, 2 )
3

See Also
--------
Loading