Skip to content

Basic support for axis simplification and arbitrary order in iterators #979

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 8 commits into
base: master
Choose a base branch
from
Prev Previous commit
Next Next commit
FEAT: Add dimension::squeeze to remove dimensions with len == 1
  • Loading branch information
bluss committed Mar 31, 2024
commit d223bc61c33fe2c0bb694abceee37238456edd77
69 changes: 69 additions & 0 deletions src/dimension/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,6 +785,43 @@ where D: Dimension
}
}

/// Remove axes with length one, except never removing the last axis.
///
/// This only has effect on dynamic dimensions.
pub(crate) fn squeeze<D>(dim: &mut D, strides: &mut D)
where D: Dimension
{
if let Some(_) = D::NDIM {
return;
}
debug_assert_eq!(dim.ndim(), strides.ndim());

// Count axes with dim == 1; we keep axes with d == 0 or d > 1
let mut ndim_new = 0;
for &d in dim.slice() {
if d != 1 {
ndim_new += 1;
}
}
ndim_new = Ord::max(1, ndim_new);
let mut new_dim = D::zeros(ndim_new);
let mut new_strides = D::zeros(ndim_new);
let mut i = 0;
for (&d, &s) in izip!(dim.slice(), strides.slice()) {
if d != 1 {
new_dim[i] = d;
new_strides[i] = s;
i += 1;
}
}
if i == 0 {
new_dim[i] = 1;
new_strides[i] = 1;
}
*dim = new_dim;
*strides = new_strides;
}

#[cfg(test)]
mod test
{
Expand All @@ -797,6 +834,7 @@ mod test
slice_min_max,
slices_intersect,
solve_linear_diophantine_eq,
squeeze,
IntoDimension,
};
use crate::error::{from_kind, ErrorKind};
Expand Down Expand Up @@ -1146,4 +1184,35 @@ mod test
s![.., 3..;6, NewAxis]
));
}

#[test]
#[cfg(feature = "std")]
fn test_squeeze()
{
let dyndim = Dim::<&[usize]>;

let mut d = dyndim(&[1, 2, 1, 1, 3, 1]);
let mut s = dyndim(&[!0, !0, !0, 9, 10, !0]);
let dans = dyndim(&[2, 3]);
let sans = dyndim(&[!0, 10]);
squeeze(&mut d, &mut s);
assert_eq!(d, dans);
assert_eq!(s, sans);

let mut d = dyndim(&[1, 1]);
let mut s = dyndim(&[3, 4]);
let dans = dyndim(&[1]);
let sans = dyndim(&[1]);
squeeze(&mut d, &mut s);
assert_eq!(d, dans);
assert_eq!(s, sans);

let mut d = dyndim(&[0, 1, 3, 4]);
let mut s = dyndim(&[2, 3, 4, 5]);
let dans = dyndim(&[0, 3, 4]);
let sans = dyndim(&[2, 4, 5]);
squeeze(&mut d, &mut s);
assert_eq!(d, dans);
assert_eq!(s, sans);
}
}
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy