Skip to main content

tenferro_tensor_core/
axis.rs

1//! Signed public axes and their normalization (#2552).
2//!
3//! Every public argument that names an axis is an `isize`: a non-negative
4//! value counts from the front and a negative value counts from the end
5//! (`-1` is the last axis), as in NumPy. Lengths, extents, shapes and IR
6//! identifiers stay `usize`. Operations normalize a signed axis to an index
7//! with [`normalize_axis`] or [`normalize_axes`] and nowhere else.
8
9use tinyvec::TinyVec;
10
11use crate::{ValidationError, INLINE_RANK};
12
13/// Small vector of signed public axes with inline capacity for common ranks.
14///
15/// # Examples
16///
17/// ```rust
18/// use tenferro_tensor_core::AxisVec;
19///
20/// let axes: AxisVec = [0, -1].into_iter().collect();
21/// assert_eq!(axes.as_slice(), &[0, -1]);
22/// ```
23pub type AxisVec = TinyVec<[isize; INLINE_RANK]>;
24
25/// Normalize one signed axis against `rank`.
26///
27/// `axis` in `0..rank` is returned unchanged; `axis` in `-rank..0` counts
28/// from the end.
29///
30/// # Errors
31///
32/// Returns [`ValidationError::AxisOutOfBounds`] carrying the caller's original
33/// signed `axis` when it is outside `-rank..rank`.
34///
35/// # Examples
36///
37/// ```rust
38/// use tenferro_tensor_core::{normalize_axis, ValidationError};
39///
40/// assert_eq!(normalize_axis(1, 3).unwrap(), 1);
41/// assert_eq!(normalize_axis(-1, 3).unwrap(), 2);
42/// assert_eq!(
43///     normalize_axis(-4, 3),
44///     Err(ValidationError::AxisOutOfBounds { axis: -4, rank: 3 })
45/// );
46/// ```
47pub fn normalize_axis(axis: isize, rank: usize) -> Result<usize, ValidationError> {
48    let out_of_bounds = ValidationError::AxisOutOfBounds { axis, rank };
49    if axis >= 0 {
50        let index = axis.unsigned_abs();
51        if index < rank {
52            Ok(index)
53        } else {
54            Err(out_of_bounds)
55        }
56    } else {
57        let from_end = axis.unsigned_abs();
58        if from_end <= rank {
59            Ok(rank - from_end)
60        } else {
61            Err(out_of_bounds)
62        }
63    }
64}
65
66/// Normalize a list of signed axes against `rank`, rejecting duplicates.
67///
68/// The result keeps the order of `axes`. Two entries that name the same axis
69/// (for example `1` and `-2` at rank 3) are a duplicate.
70///
71/// # Errors
72///
73/// Returns [`ValidationError::AxisOutOfBounds`] for the first entry outside
74/// `-rank..rank`, and [`ValidationError::DuplicateAxis`] (role `"axes"`,
75/// normalized index) for the first repeated axis.
76///
77/// # Examples
78///
79/// ```rust
80/// use tenferro_tensor_core::{normalize_axes, ValidationError};
81///
82/// assert_eq!(normalize_axes(&[0, -1], 3).unwrap().as_slice(), &[0, 2]);
83/// assert_eq!(
84///     normalize_axes(&[1, -2], 3),
85///     Err(ValidationError::DuplicateAxis { axis: 1, role: "axes" })
86/// );
87/// ```
88pub fn normalize_axes(
89    axes: &[isize],
90    rank: usize,
91) -> Result<TinyVec<[usize; INLINE_RANK]>, ValidationError> {
92    let mut normalized = TinyVec::<[usize; INLINE_RANK]>::new();
93    for &axis in axes {
94        let index = normalize_axis(axis, rank)?;
95        // INVARIANT: `normalized.len() <= rank`, and public axis lists are
96        // bounded by the tensor rank, so this scan is rank-bounded quadratic.
97        if normalized.contains(&index) {
98            return Err(ValidationError::DuplicateAxis {
99                axis: index,
100                role: "axes",
101            });
102        }
103        normalized.push(index);
104    }
105    Ok(normalized)
106}
107
108#[cfg(test)]
109mod tests;