Skip to main content

ruxla_core/
jnp.rs

1//! Functions following `jax.numpy`, with NumPy's broadcasting.
2//!
3//! Operands are anything that converts to an array ([`ArrayLike`]): arrays,
4//! scalars, and Rust values of the element type. At least one operand must
5//! be an array or a scalar, which fixes the backend.
6
7pub mod fft;
8
9use ruxla_ir::{DotDims, GatherDims, GatherScatterMode, RoundingMethod, Shape};
10use ruxla_kernels::{BinaryOp, Element, UnaryOp, bf16, f16};
11
12use crate::backend::Backend;
13
14pub mod linalg;
15use crate::lax;
16use crate::value::{
17    Array, ArrayLike, ComplexFloat, Float, Inexact, Int, Num, Numeric, Scalar, broadcast_binary,
18    broadcast_compare, broadcast_shapes,
19};
20
21/// Axes of a reduction: all of them, or a list (negative values count from
22/// the end).
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub enum Axes {
25    /// Every axis.
26    All,
27    /// These axes.
28    Some(Vec<i64>),
29    /// At most eight axes, stored without allocating (what the `From`
30    /// conversions give).
31    Few(AxisList),
32}
33
34/// At most eight axes, stored without allocating.
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub struct AxisList {
37    len: u8,
38    axes: [i64; 8],
39}
40
41impl AxisList {
42    /// The axes, or `None` for more than eight.
43    pub fn new(axes: &[i64]) -> Option<Self> {
44        let mut out = AxisList {
45            len: axes.len() as u8,
46            axes: [0; 8],
47        };
48        out.axes.get_mut(..axes.len())?.copy_from_slice(axes);
49        Some(out)
50    }
51
52    /// The axes.
53    pub fn as_slice(&self) -> &[i64] {
54        &self.axes[..usize::from(self.len)]
55    }
56}
57
58impl Axes {
59    fn of(a: &[i64]) -> Self {
60        AxisList::new(a).map_or_else(|| Axes::Some(a.to_vec()), Axes::Few)
61    }
62
63    /// The axes given (`None` for every axis).
64    pub fn as_slice(&self) -> Option<&[i64]> {
65        match self {
66            Axes::All => None,
67            Axes::Some(a) => Some(a),
68            Axes::Few(a) => Some(a.as_slice()),
69        }
70    }
71}
72
73/// Every axis.
74pub const ALL: Axes = Axes::All;
75
76impl From<i64> for Axes {
77    fn from(a: i64) -> Self {
78        Axes::of(&[a])
79    }
80}
81
82impl From<i32> for Axes {
83    fn from(a: i32) -> Self {
84        Axes::of(&[i64::from(a)])
85    }
86}
87
88impl From<&[i64]> for Axes {
89    fn from(a: &[i64]) -> Self {
90        Axes::of(a)
91    }
92}
93
94impl<const N: usize> From<[i64; N]> for Axes {
95    fn from(a: [i64; N]) -> Self {
96        Axes::of(&a)
97    }
98}
99
100/// Normalizes an axis (negative counts from the end).
101#[track_caller]
102pub(crate) fn normalize_axis(axis: i64, rank: usize) -> usize {
103    let r = rank as i64;
104    assert!(
105        (-r..r).contains(&axis),
106        "axis {axis} is out of range for rank {rank}"
107    );
108    (if axis < 0 { axis + r } else { axis }) as usize
109}
110
111impl Axes {
112    #[track_caller]
113    fn resolve(&self, rank: usize) -> Shape {
114        match self.as_slice() {
115            None => (0..rank).collect(),
116            Some(a) => {
117                let mut v: Shape = a.iter().map(|&x| normalize_axis(x, rank)).collect();
118                // Few axes: an insertion sort, without allocating.
119                for i in 1..v.rank() {
120                    let mut j = i;
121                    while j > 0 && v[j - 1] > v[j] {
122                        let (a, b) = (v[j - 1], v[j]);
123                        v.set(j - 1, b);
124                        v.set(j, a);
125                        j -= 1;
126                    }
127                }
128                v
129            }
130        }
131    }
132}
133
134/// An array of `shape` filled with `value`.
135pub fn full<B: Backend, T: Element>(
136    shape: impl Into<Shape>,
137    value: impl Into<Scalar<B, T>>,
138) -> Array<B, T> {
139    let shape = shape.into();
140    let value = value.into();
141    if B::FAST_PATHS
142        && let Some(x) = B::full::<T>(shape.clone(), value.0)
143    {
144        return Array(x);
145    }
146    let s = value.to_array();
147    if shape.rank() == 0 {
148        return s;
149    }
150    lax::broadcast_in_dim(&s, shape, &[])
151}
152
153/// An array of zeros.
154pub fn zeros<B: Backend, T: Element>(shape: impl Into<Shape>) -> Array<B, T> {
155    full(shape, Scalar::new(ruxla_kernels::cast::<u8, T>(0)))
156}
157
158/// An array of ones.
159pub fn ones<B: Backend, T: Element>(shape: impl Into<Shape>) -> Array<B, T> {
160    full(shape, Scalar::new(ruxla_kernels::cast::<u8, T>(1)))
161}
162
163/// `0, 1, ..., n - 1`.
164pub fn arange<B: Backend, T: Num>(n: usize) -> Array<B, T> {
165    lax::iota([n], 0)
166}
167
168/// Converts to another element type.
169pub fn astype<B: Backend, T: Element, U: Element>(x: impl ArrayLike<B, T>) -> Array<B, U> {
170    x.into_array().cast()
171}
172
173/// Broadcasts to `shape`.
174#[track_caller]
175pub fn broadcast_to<B: Backend, T: Element>(
176    x: impl ArrayLike<B, T>,
177    shape: impl Into<Shape>,
178) -> Array<B, T> {
179    x.into_array().broadcast_to(shape)
180}
181
182macro_rules! unary {
183    ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
184        $(#[$m])*
185        pub fn $name<B: Backend, T: $bound>(x: impl ArrayLike<B, T>) -> Array<B, T> {
186            x.with_array(|x| x.unary(UnaryOp::$op))
187        }
188    )*};
189}
190
191unary! { Numeric:
192    /// `-x`.
193    negative => Neg;
194    /// The sign (`x / |x|` for complex numbers).
195    sign => Sign;
196    /// `x * x`.
197    square => Square;
198}
199
200/// `|x|` (unsigned values are returned unchanged; the magnitude of a
201/// complex number is real).
202pub fn abs<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
203    x.with_array(|x| x.abs())
204}
205
206/// The real parts of complex numbers.
207pub fn real<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
208    x.with_array(|x| x.real())
209}
210
211/// The imaginary parts of complex numbers.
212pub fn imag<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
213    x.with_array(|x| x.imag())
214}
215
216/// The complex conjugates.
217pub fn conj<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T> {
218    x.with_array(|x| x.conj())
219}
220
221/// The complex conjugates (`jnp.conjugate`, the same as [`conj`]).
222pub fn conjugate<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T> {
223    conj(x)
224}
225
226/// The arguments of complex numbers (`atan2(imag, real)`), in radians.
227pub fn angle<B: Backend, T: ComplexFloat>(x: impl ArrayLike<B, T>) -> Array<B, T::Real> {
228    x.with_array(|x| x.angle())
229}
230
231unary! { Float:
232    /// Round down.
233    floor => Floor;
234    /// Round up.
235    ceil => Ceil;
236    /// Round, halfway cases to even (NumPy's rounding).
237    round => RoundEven;
238    /// Cube root.
239    cbrt => Cbrt;
240}
241
242unary! { Inexact:
243    /// `e^x`.
244    exp => Exp;
245    /// `e^x - 1`.
246    expm1 => Expm1;
247    /// Natural logarithm.
248    log => Log;
249    /// `log(1 + x)`.
250    log1p => Log1p;
251    /// Square root.
252    sqrt => Sqrt;
253    /// Sine.
254    sin => Sin;
255    /// Cosine.
256    cos => Cos;
257    /// Tangent.
258    tan => Tan;
259    /// Hyperbolic tangent.
260    tanh => Tanh;
261}
262
263/// Logical not.
264pub fn logical_not<B: Backend>(x: impl ArrayLike<B, bool>) -> Array<B, bool> {
265    x.into_array().unary(UnaryOp::Not)
266}
267
268/// Whether each element is finite.
269pub fn isfinite<B: Backend, T: Float>(x: impl ArrayLike<B, T>) -> Array<B, bool> {
270    lax::is_finite(&x.into_array())
271}
272
273macro_rules! binary {
274    ($bound:ident: $($(#[$m:meta])* $name:ident => $op:ident;)*) => {$(
275        $(#[$m])*
276        #[track_caller]
277        pub fn $name<B: Backend, T: $bound>(x: impl ArrayLike<B, T>, y: impl ArrayLike<B, T>) -> Array<B, T> {
278            x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::$op, x, y)))
279        }
280    )*};
281}
282
283binary! { Numeric:
284    /// `x + y`.
285    add => Add;
286    /// `x - y`.
287    subtract => Sub;
288    /// `x * y`.
289    multiply => Mul;
290}
291
292binary! { Num:
293    /// The remainder of truncated division, with the sign of `x` (C's `fmod`).
294    fmod => Rem;
295}
296
297binary! { Inexact:
298    /// `x / y`.
299    divide => Div;
300    /// `x^y`.
301    power => Pow;
302}
303
304binary! { Float:
305    /// `atan2(x, y)`.
306    arctan2 => Atan2;
307}
308
309binary! { Element:
310    /// The maximum, propagating NaN.
311    maximum => Max;
312    /// The minimum, propagating NaN.
313    minimum => Min;
314}
315
316/// Logical and.
317#[track_caller]
318pub fn logical_and<B: Backend>(
319    x: impl ArrayLike<B, bool>,
320    y: impl ArrayLike<B, bool>,
321) -> Array<B, bool> {
322    x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::And, x, y)))
323}
324
325/// Logical or.
326#[track_caller]
327pub fn logical_or<B: Backend>(
328    x: impl ArrayLike<B, bool>,
329    y: impl ArrayLike<B, bool>,
330) -> Array<B, bool> {
331    x.with_array(|x| y.with_array(|y| broadcast_binary(BinaryOp::Or, x, y)))
332}
333
334/// Integer division rounding toward negative infinity, computed as JAX
335/// does: `div`, minus one where the signs of `x` and `y` differ and the
336/// remainder is nonzero (so `x // 0` is -2 for `x != 0`; unsigned integers
337/// only `div`).
338///
339/// # Examples
340///
341/// ```
342/// use ruxla_core::{Array, Native, jnp};
343///
344/// let x = Array::<Native, i32>::from_slice(&[7, -7, 5, 0, -5], [5]);
345/// let y = Array::<Native, i32>::from_slice(&[2, 2, 0, 0, 0], [5]);
346/// assert_eq!(jnp::floor_divide(&x, &y).to_vec(), [3, -4, -2, -1, -2]);
347/// ```
348#[track_caller]
349pub fn floor_divide<B: Backend, T: Int>(
350    x: impl ArrayLike<B, T>,
351    y: impl ArrayLike<B, T>,
352) -> Array<B, T> {
353    let (x, y) = (x.into_array(), y.into_array());
354    let q = broadcast_binary(BinaryOp::Div, &x, &y);
355    if T::DTYPE.kind() == ruxla_kernels::DTypeKind::UnsignedInt {
356        return q;
357    }
358    let r = broadcast_binary(BinaryOp::Rem, &x, &y);
359    let zero = zeros::<B, T>(r.shape());
360    // Round down when the remainder is nonzero and the signs differ.
361    let adjust = broadcast_compare(ruxla_kernels::CompareOp::Ne, &r, &zero)
362        & broadcast_compare(ruxla_kernels::CompareOp::Ne, &x.sign(), &y.sign());
363    where_(adjust, &q - Scalar::new(ruxla_kernels::cast::<u8, T>(1)), q)
364}
365
366/// The remainder with the sign of `y` (Python's `%`, `jnp.remainder`):
367/// `x - floor(x / y) * y`, computed as JAX does (`rem`, adding `y` where the
368/// signs differ; an integer `y` of zero is replaced by one).
369///
370/// # Examples
371///
372/// ```
373/// use ruxla_core::{I32, Native, jnp};
374///
375/// let r = jnp::remainder(I32::<Native>::new(-7), I32::new(3));
376/// assert_eq!(r.to_vec(), [2]);
377/// ```
378#[track_caller]
379pub fn remainder<B: Backend, T: Num>(
380    x: impl ArrayLike<B, T>,
381    y: impl ArrayLike<B, T>,
382) -> Array<B, T> {
383    let zero = ruxla_kernels::cast::<u8, T>(0);
384    let one = ruxla_kernels::cast::<u8, T>(1);
385    let int = !T::DTYPE.is_float();
386    if B::FAST_PATHS
387        && let (Some(a), Some(b)) = (x.as_scalar(), y.as_scalar())
388    {
389        let lt = |v| B::compare::<T>(ruxla_kernels::CompareOp::Lt, v, B::lit(zero));
390        let ne = |v| B::compare::<T>(ruxla_kernels::CompareOp::Ne, v, B::lit(zero));
391        let b = if int {
392            B::select(
393                B::compare::<T>(ruxla_kernels::CompareOp::Eq, b.0, B::lit(zero)),
394                B::lit(one),
395                b.0,
396            )
397        } else {
398            b.0
399        };
400        let r = B::binary::<T>(BinaryOp::Rem, a.0, b);
401        let plus = B::binary::<bool>(
402            BinaryOp::And,
403            B::compare::<bool>(ruxla_kernels::CompareOp::Ne, lt(r), lt(b)),
404            ne(r),
405        );
406        return Scalar(B::select(plus, B::binary::<T>(BinaryOp::Add, r, b), r)).to_array();
407    }
408    let (x, y) = (x.into_array(), y.into_array());
409    let y = if int {
410        let z = zeros::<B, T>(y.shape());
411        where_(
412            broadcast_compare(ruxla_kernels::CompareOp::Eq, &y, &z),
413            Scalar::<B, T>::new(one),
414            &y,
415        )
416    } else {
417        y
418    };
419    let r = broadcast_binary(BinaryOp::Rem, &x, &y);
420    let rz = zeros::<B, T>(r.shape());
421    let not_zero = broadcast_compare(ruxla_kernels::CompareOp::Ne, &r, &rz);
422    let yz = zeros::<B, T>(y.shape());
423    let plus = broadcast_compare(
424        ruxla_kernels::CompareOp::Ne,
425        &r.lt(&rz),
426        &y.lt(&yz).broadcast_to(r.shape()),
427    ) & not_zero;
428    where_(plus, broadcast_binary(BinaryOp::Add, &r, &y), r)
429}
430
431/// `cond ? x : y` elementwise, with broadcasting.
432#[track_caller]
433pub fn where_<B: Backend, T: Element>(
434    cond: impl ArrayLike<B, bool>,
435    x: impl ArrayLike<B, T>,
436    y: impl ArrayLike<B, T>,
437) -> Array<B, T> {
438    let (c, x, y) = (cond.into_array(), x.into_array(), y.into_array());
439    if B::FAST_PATHS
440        && let Some(r) = B::a_select_broadcast::<T>(&c.0, &x.0, &y.0)
441    {
442        return Array(r);
443    }
444    let s = broadcast_shapes(&broadcast_shapes(&c.shape(), &x.shape()), &y.shape());
445    lax::select_array(
446        &c.broadcast_to(s.clone()),
447        &x.broadcast_to(s.clone()),
448        &y.broadcast_to(s),
449    )
450}
451
452/// Clamps to `[lo, hi]` (`maximum` then `minimum`, propagating NaN).
453#[track_caller]
454pub fn clip<B: Backend, T: Element>(
455    x: impl ArrayLike<B, T>,
456    lo: impl ArrayLike<B, T>,
457    hi: impl ArrayLike<B, T>,
458) -> Array<B, T> {
459    if B::FAST_PATHS
460        && let (Some(x), Some(lo), Some(hi)) = (x.as_scalar(), lo.as_scalar(), hi.as_scalar())
461    {
462        return Scalar(B::binary::<T>(
463            BinaryOp::Min,
464            B::binary::<T>(BinaryOp::Max, x.0, lo.0),
465            hi.0,
466        ))
467        .to_array();
468    }
469    minimum(maximum(x, lo), hi)
470}
471
472/// Whether two arrays are equal elementwise.
473#[track_caller]
474pub fn equal<B: Backend, T: Element>(
475    x: impl ArrayLike<B, T>,
476    y: impl ArrayLike<B, T>,
477) -> Array<B, bool> {
478    broadcast_compare(
479        ruxla_kernels::CompareOp::Eq,
480        &x.into_array(),
481        &y.into_array(),
482    )
483}
484
485fn is_half<T: Element>() -> bool {
486    T::DTYPE == f16::DTYPE || T::DTYPE == bf16::DTYPE
487}
488
489/// Sums over `axes`. 16-bit floats accumulate in `f32`, as in JAX.
490#[track_caller]
491pub fn sum<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
492    let x = x.into_array();
493    let axes = axes.into().resolve(x.ndim());
494    if is_half::<T>() {
495        return x.cast::<f32>().reduce_sum(&axes).cast::<T>();
496    }
497    x.reduce_sum(&axes)
498}
499
500/// Averages over `axes`, in the input type (16-bit floats in `f32`).
501#[track_caller]
502pub fn mean<B: Backend, T: Float>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
503    let x = x.into_array();
504    let shape = x.shape();
505    let axes = axes.into().resolve(shape.rank());
506    let n: usize = axes.iter().map(|&a| shape[a]).product();
507    if is_half::<T>() {
508        let total = x.cast::<f32>().reduce_sum(&axes);
509        return (total / n as f32).cast::<T>();
510    }
511    let total = x.reduce_sum(&axes);
512    total / Scalar::<B, T>::new(ruxla_kernels::cast::<u64, T>(n as u64))
513}
514
515/// The maximum over `axes`.
516#[track_caller]
517pub fn max<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
518    let x = x.into_array();
519    let axes = axes.into().resolve(x.ndim());
520    x.reduce_max(&axes)
521}
522
523/// The minimum over `axes`.
524#[track_caller]
525pub fn min<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axes: impl Into<Axes>) -> Array<B, T> {
526    let x = x.into_array();
527    let axes = axes.into().resolve(x.ndim());
528    x.reduce_min(&axes)
529}
530
531/// Whether any element along `axes` is true.
532#[track_caller]
533pub fn any<B: Backend>(x: impl ArrayLike<B, bool>, axes: impl Into<Axes>) -> Array<B, bool> {
534    max(x, axes)
535}
536
537/// Whether every element along `axes` is true.
538#[track_caller]
539pub fn all<B: Backend>(x: impl ArrayLike<B, bool>, axes: impl Into<Axes>) -> Array<B, bool> {
540    min(x, axes)
541}
542
543/// The index (`i32`) of the largest element along `axis`.
544#[track_caller]
545pub fn argmax<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, i32> {
546    let x = x.into_array();
547    let axis = normalize_axis(axis, x.ndim());
548    lax::argmax(&x, axis)
549}
550
551/// The index (`i32`) of the smallest element along `axis`.
552#[track_caller]
553pub fn argmin<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, i32> {
554    let x = x.into_array();
555    let axis = normalize_axis(axis, x.ndim());
556    lax::argmin(&x, axis)
557}
558
559/// The array to accumulate and the axis, as NumPy's cumulative functions
560/// take them: `None` (or a scalar) accumulates the flattened array.
561#[track_caller]
562fn cumulative_operand<B: Backend, T: Element>(
563    x: impl ArrayLike<B, T>,
564    axis: Option<i64>,
565) -> (Array<B, T>, usize) {
566    let x = x.into_array();
567    if axis.is_none() || x.ndim() == 0 {
568        let n = x.size();
569        let flat = lax::reshape(&x, [n]);
570        let axis = normalize_axis(axis.unwrap_or(0), 1);
571        return (flat, axis);
572    }
573    let axis = normalize_axis(axis.unwrap_or(0), x.ndim());
574    (x, axis)
575}
576
577/// The cumulative sum along `axis` (of the flattened array for `None`), in
578/// the input type.
579///
580/// # Examples
581///
582/// ```
583/// use ruxla_core::{Array, Native, jnp};
584///
585/// let x = Array::<Native, f32>::from_vec(vec![1.0, 2.0, 3.0, 4.0], [2, 2]);
586/// assert_eq!(jnp::cumsum(&x, Some(1)).to_vec(), [1.0, 3.0, 3.0, 7.0]);
587/// assert_eq!(jnp::cumsum(&x, None).to_vec(), [1.0, 3.0, 6.0, 10.0]);
588/// ```
589#[track_caller]
590pub fn cumsum<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axis: Option<i64>) -> Array<B, T> {
591    let (x, axis) = cumulative_operand(x, axis);
592    lax::cumsum(&x, axis, false)
593}
594
595/// The cumulative product along `axis` (of the flattened array for
596/// `None`), in the input type.
597#[track_caller]
598pub fn cumprod<B: Backend, T: Numeric>(x: impl ArrayLike<B, T>, axis: Option<i64>) -> Array<B, T> {
599    let (x, axis) = cumulative_operand(x, axis);
600    lax::cumprod(&x, axis, false)
601}
602
603/// Inserts a dimension of size 1 at `axis`.
604#[track_caller]
605pub fn expand_dims<B: Backend, T: Element>(x: impl ArrayLike<B, T>, axis: i64) -> Array<B, T> {
606    let x = x.into_array();
607    let shape = x.shape();
608    let axis = normalize_axis(axis, shape.rank() + 1);
609    let mut out = shape.clone();
610    out.insert(axis, 1);
611    let dims: Shape = (0..shape.rank())
612        .map(|i| if i < axis { i } else { i + 1 })
613        .collect();
614    lax::broadcast_in_dim(&x, out, &dims)
615}
616
617/// Stacks arrays (or scalars) along a new dimension `axis`.
618///
619/// # Panics
620///
621/// Panics if `xs` is empty or the shapes differ.
622#[track_caller]
623#[inline]
624pub fn stack<B: Backend, T: Element, A: ArrayLike<B, T> + Clone>(
625    xs: &[A],
626    axis: i64,
627) -> Array<B, T> {
628    assert!(!xs.is_empty(), "stack needs at least one array");
629    if B::FAST_PATHS && (axis == 0 || axis == -1) && xs.iter().all(|x| x.as_scalar().is_some()) {
630        let r = B::stack_scalars::<T>(xs.len(), |i| xs[i].as_scalar().expect("a scalar").0);
631        if let Some(r) = r {
632            return Array(r);
633        }
634    }
635    stack_general(xs, axis)
636}
637
638/// [`stack`] without the fast path for scalars.
639#[track_caller]
640fn stack_general<B: Backend, T: Element, A: ArrayLike<B, T> + Clone>(
641    xs: &[A],
642    axis: i64,
643) -> Array<B, T> {
644    if B::FAST_PATHS && (axis == 0 || axis == -1 && xs[0].clone().into_array().ndim() == 0) {
645        let arrays: Vec<Array<B, T>> = xs.iter().map(|x| x.clone().into_array()).collect();
646        if let Some(r) = B::stack0::<T>(Array::reprs(&arrays)) {
647            return Array(r);
648        }
649    }
650    let parts: Vec<Array<B, T>> = xs.iter().map(|x| expand_dims(x.clone(), axis)).collect();
651    let axis = normalize_axis(axis, parts[0].ndim());
652    lax::concatenate(&parts, axis)
653}
654
655/// The elements of `x` at `indices` along `axis` (`jnp.take(x, indices,
656/// axis, mode="clip")`, which is JAX's indexing `x[..., indices, ...]`):
657/// the result has the shape of `x` with dimension `axis` replaced by the
658/// shape of `indices`. Negative indices count from the end, and indices out
659/// of bounds are clamped.
660///
661/// # Examples
662///
663/// ```
664/// use ruxla_core::{Array, Native, jnp};
665///
666/// let x = Array::<Native, i32>::from_slice(&[10, 11, 12, 13, 14, 15], [3, 2]);
667/// let i = Array::<Native, i32>::from_slice(&[2, -3], [2]);
668/// assert_eq!(jnp::take(&x, &i, 0).to_vec(), [14, 15, 10, 11]);
669/// ```
670///
671/// # Panics
672///
673/// Panics if `axis` is out of range.
674#[track_caller]
675pub fn take<B: Backend, T: Element, I: Int>(
676    x: &Array<B, T>,
677    indices: &Array<B, I>,
678    axis: i64,
679) -> Array<B, T> {
680    let shape = x.shape();
681    let rank = shape.rank();
682    let axis = if axis < 0 { axis + rank as i64 } else { axis };
683    assert!(
684        (0..rank as i64).contains(&axis),
685        "take: axis {axis} out of range for rank {rank}"
686    );
687    let axis = axis as usize;
688    if B::FAST_PATHS
689        && let Some(r) = B::a_take::<T, I>(&x.0, &indices.0, axis)
690    {
691        return Array(r);
692    }
693    let n = shape.dims()[axis];
694    let indices = indices.cast::<i32>();
695    let indices = where_(indices.lt(0i32), indices.clone() + n as i32, indices);
696    let index_rank = indices.ndim();
697    let mut dims_of_indices = indices.shape().dims().to_vec();
698    dims_of_indices.push(1);
699    let offset_dims = (0..axis)
700        .chain(axis + index_rank..rank - 1 + index_rank)
701        .collect();
702    let dims = GatherDims {
703        offset_dims,
704        collapsed_slice_dims: vec![axis],
705        start_index_map: vec![axis],
706        ..GatherDims::default()
707    };
708    let mut slice_sizes = shape.dims().to_vec();
709    slice_sizes[axis] = 1;
710    lax::gather(
711        x,
712        &indices.reshape(dims_of_indices),
713        &dims,
714        &slice_sizes,
715        GatherScatterMode::Clip,
716    )
717}
718
719/// `x` with the elements along `axis` moved by a static `shift` toward
720/// higher indices, wrapping around (`jnp.roll(x, shift, axis)`): element `i`
721/// goes to `(i + shift) mod n`. As in JAX, it is two slices and a
722/// concatenation.
723///
724/// # Examples
725///
726/// ```
727/// use ruxla_core::{Array, Native, jnp};
728///
729/// let x = Array::<Native, i32>::from_slice(&[0, 1, 2, 3, 4], [5]);
730/// assert_eq!(jnp::roll(&x, 2, 0).to_vec(), [3, 4, 0, 1, 2]);
731/// assert_eq!(jnp::roll(&x, -1, 0).to_vec(), [1, 2, 3, 4, 0]);
732/// ```
733///
734/// # Panics
735///
736/// Panics if `axis` is out of range.
737#[track_caller]
738#[inline]
739pub fn roll<B: Backend, T: Element>(x: &Array<B, T>, shift: i64, axis: i64) -> Array<B, T> {
740    if B::FAST_PATHS
741        && let Some(dims) = B::dims(&x.0)
742    {
743        let axis = normalize_axis(axis, dims.len());
744        let n = dims[axis];
745        let i = roll_start(shift, n);
746        if i == 0 {
747            return x.clone();
748        }
749        if let Some(r) = B::a_roll::<T>(&x.0, n - i, axis) {
750            return Array(r);
751        }
752    }
753    roll_general(x, shift, axis)
754}
755
756/// Where the result of a roll by `shift` of `n` elements starts, as JAX's
757/// `_roll_static` computes it (0 for no change).
758#[inline]
759fn roll_start(shift: i64, n: usize) -> usize {
760    shift.wrapping_neg().rem_euclid(n.max(1) as i64) as usize
761}
762
763/// [`roll`] without the fast path: the slice from the start to the end,
764/// then the rest.
765#[track_caller]
766fn roll_general<B: Backend, T: Element>(x: &Array<B, T>, shift: i64, axis: i64) -> Array<B, T> {
767    let shape = x.shape();
768    let axis = normalize_axis(axis, shape.rank());
769    let n = shape.dims()[axis];
770    let i = roll_start(shift, n);
771    if i == 0 {
772        return x.clone();
773    }
774    lax::concatenate(
775        &[
776            lax::slice_in_dim(x, i, n, 1, axis),
777            lax::slice_in_dim(x, 0, i, 1, axis),
778        ],
779        axis,
780    )
781}
782
783/// Joins arrays along `axis`.
784#[track_caller]
785pub fn concatenate<B: Backend, T: Element>(xs: &[Array<B, T>], axis: i64) -> Array<B, T> {
786    assert!(!xs.is_empty(), "concatenate needs at least one array");
787    let axis = normalize_axis(axis, xs[0].ndim());
788    lax::concatenate(xs, axis)
789}
790
791/// Matrix product with NumPy's rules for vectors and matrices.
792///
793/// # Panics
794///
795/// Panics for scalars, arrays of rank above 2, or mismatched dimensions.
796#[track_caller]
797pub fn matmul<B: Backend, T: Numeric>(a: &Array<B, T>, b: &Array<B, T>) -> Array<B, T> {
798    let (ra, rb) = (a.ndim(), b.ndim());
799    assert!(
800        (1..=2).contains(&ra) && (1..=2).contains(&rb),
801        "matmul supports ranks 1 and 2, got {ra} and {rb}"
802    );
803    let dims = DotDims {
804        lhs_contracting: vec![ra - 1],
805        rhs_contracting: vec![0],
806        ..DotDims::default()
807    };
808    lax::dot_general(a, b, &dims)
809}
810
811/// Rounds with the given method (`round` with a method, for completeness).
812pub fn round_with<B: Backend, T: Float>(
813    x: impl ArrayLike<B, T>,
814    method: RoundingMethod,
815) -> Array<B, T> {
816    let op = match method {
817        RoundingMethod::AwayFromZero => UnaryOp::Round,
818        RoundingMethod::ToNearestEven => UnaryOp::RoundEven,
819    };
820    x.into_array().unary(op)
821}
822
823impl<B: Backend, T: Numeric> Array<B, T> {
824    /// Matrix product (`jnp.matmul`).
825    #[track_caller]
826    pub fn dot(&self, other: &Array<B, T>) -> Array<B, T> {
827        matmul(self, other)
828    }
829
830    /// Sums over `axes` (`jnp.sum`).
831    #[track_caller]
832    pub fn sum(&self, axes: impl Into<Axes>) -> Array<B, T> {
833        sum(self, axes)
834    }
835}