Skip to main content

ruxla_core/
value.rs

1//! The value types: [`Scalar`] and [`Array`].
2
3use std::fmt;
4use std::ops;
5
6use ruxla_ir::Shape;
7use ruxla_kernels::array::ReduceOp;
8use ruxla_kernels::{BinaryOp, CompareOp, Element, UnaryOp, bf16, c64, c128, f16};
9
10use crate::backend::{Backend, Native, NativeArray, ToReal};
11
12/// Element types that are floating point numbers.
13pub trait Float: Num + Inexact {}
14impl Float for f16 {}
15impl Float for bf16 {}
16impl Float for f32 {}
17impl Float for f64 {}
18
19/// The real element types of linear algebra (`lax::linalg`,
20/// `jnp::linalg`): `f32` and `f64`.
21pub trait LinalgFloat: Float + LinalgScalar + ruxla_kernels::linalg::LinalgFloat {}
22impl LinalgFloat for f32 {}
23impl LinalgFloat for f64 {}
24
25/// The element types of the linear algebra primitives (`lax::linalg`):
26/// `f32`, `f64`, `c64`, and `c128`. The eigenvalues of `eigh` and the
27/// singular values of `svd` have the real type `Real`.
28pub trait LinalgScalar:
29    Inexact
30    + ruxla_kernels::linalg::LinalgScalar<LinalgReal: Float + ruxla_kernels::linalg::LinalgFloat>
31{
32    /// The complex type of the results of `eig` (`c64` for `f32` and
33    /// `c64`, `c128` for `f64` and `c128`).
34    type Complex: ComplexFloat;
35    /// The values of the kernel's complex type as `Complex` (the same type).
36    #[doc(hidden)]
37    fn complex_vec(v: Vec<ruxla_kernels::linalg::Cx<Self>>) -> Vec<Self::Complex>;
38}
39macro_rules! impl_linalg_scalar {
40    ($($t:ty => $c:ty),*) => {$(
41        impl LinalgScalar for $t {
42            type Complex = $c;
43            fn complex_vec(v: Vec<ruxla_kernels::linalg::Cx<Self>>) -> Vec<$c> {
44                v
45            }
46        }
47    )*};
48}
49impl_linalg_scalar!(f32 => c64, f64 => c128, c64 => c64, c128 => c128);
50/// Element types that are numbers: integers, floats, and complex numbers
51/// (NumPy's `number`). They have arithmetic.
52pub trait Numeric: Element {}
53macro_rules! numeric {
54    ($($t:ty)*) => {$(impl Numeric for $t {})*};
55}
56numeric!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64 c64 c128);
57
58/// Element types that are floats or complex numbers (NumPy's `inexact`).
59/// They have the transcendental functions that complex numbers share with
60/// floats (`exp`, `ln`, `sqrt`, `sin`, ...), and derivatives.
61pub trait Inexact: Numeric {}
62impl Inexact for f16 {}
63impl Inexact for bf16 {}
64impl Inexact for f32 {}
65impl Inexact for f64 {}
66impl Inexact for c64 {}
67impl Inexact for c128 {}
68
69/// Element types that are complex numbers, whose parts are [`Float`]s.
70pub trait ComplexFloat: Inexact + Element<Real: Float> {}
71impl ComplexFloat for c64 {}
72impl ComplexFloat for c128 {}
73
74/// The floats that complex numbers are made of (`f32` and `f64`), with
75/// their complex type (the result of `rfft`).
76pub trait RealFloat: Float {
77    /// The complex type with parts of this type.
78    type Complex: ComplexFloat + Element<Real = Self>;
79}
80impl RealFloat for f32 {
81    type Complex = c64;
82}
83impl RealFloat for f64 {
84    type Complex = c128;
85}
86
87/// Element types that are integers.
88pub trait Int: Num {}
89impl Int for i8 {}
90impl Int for i16 {}
91impl Int for i32 {}
92impl Int for i64 {}
93impl Int for u8 {}
94impl Int for u16 {}
95impl Int for u32 {}
96impl Int for u64 {}
97
98/// Element types that are real numbers (integers and floats; not `bool`
99/// or complex numbers).
100pub trait Num: Numeric + Element<Real = Self> {}
101macro_rules! num {
102    ($($t:ty)*) => {$(impl Num for $t {})*};
103}
104num!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64);
105
106/// A scalar of element type `T` on backend `B`.
107///
108/// On `Native` it is a `T`; on `Trace` it is a traced value. It is `Copy`
109/// on both backends.
110///
111/// # Examples
112///
113/// ```
114/// use ruxla_core::{Backend, F32, Native};
115///
116/// fn hypot<B: Backend>(x: F32<B>, y: F32<B>) -> F32<B> {
117///     (x * x + y * y).sqrt()
118/// }
119/// assert_eq!(hypot::<Native>(F32::new(3.0), F32::new(4.0)).value(), 5.0);
120/// ```
121#[repr(transparent)]
122pub struct Scalar<B: Backend, T: Element>(pub(crate) B::Scalar<T>);
123
124/// A `bool` scalar.
125pub type Bool<B> = Scalar<B, bool>;
126/// An `i32` scalar.
127pub type I32<B> = Scalar<B, i32>;
128/// An `i64` scalar.
129pub type I64<B> = Scalar<B, i64>;
130/// A `u32` scalar.
131pub type U32<B> = Scalar<B, u32>;
132/// A `u8` scalar.
133pub type U8<B> = Scalar<B, u8>;
134/// An `f32` scalar.
135pub type F32<B> = Scalar<B, f32>;
136/// An `f64` scalar.
137pub type F64<B> = Scalar<B, f64>;
138/// A `c64` (`complex64`) scalar.
139pub type C64<B> = Scalar<B, c64>;
140/// A `c128` (`complex128`) scalar.
141pub type C128<B> = Scalar<B, c128>;
142
143impl<B: Backend, T: Element> Clone for Scalar<B, T> {
144    fn clone(&self) -> Self {
145        *self
146    }
147}
148impl<B: Backend, T: Element> Copy for Scalar<B, T> {}
149
150impl<B: Backend, T: Element> fmt::Debug for Scalar<B, T> {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        write!(f, "Scalar<{}>({:?})", T::DTYPE, self.0)
153    }
154}
155
156impl<B: Backend, T: Element> From<T> for Scalar<B, T> {
157    fn from(v: T) -> Self {
158        Self::new(v)
159    }
160}
161
162impl<B: Backend, T: Element> Scalar<B, T> {
163    /// A constant.
164    pub fn new(v: T) -> Self {
165        Scalar(B::lit(v))
166    }
167
168    /// Wraps a backend value.
169    pub fn from_repr(r: B::Scalar<T>) -> Self {
170        Scalar(r)
171    }
172
173    /// Returns the backend value.
174    pub fn repr(self) -> B::Scalar<T> {
175        self.0
176    }
177
178    fn unary(self, op: UnaryOp) -> Self {
179        Scalar(B::unary::<T>(op, self.0))
180    }
181
182    fn binary(self, op: BinaryOp, other: impl Into<Self>) -> Self {
183        Scalar(B::binary::<T>(op, self.0, other.into().0))
184    }
185
186    fn compare(self, op: CompareOp, other: impl Into<Self>) -> Bool<B> {
187        Scalar(B::compare::<T>(op, self.0, other.into().0))
188    }
189
190    /// `self == other`.
191    pub fn eq(self, other: impl Into<Self>) -> Bool<B> {
192        self.compare(CompareOp::Eq, other)
193    }
194    /// `self != other`.
195    pub fn ne(self, other: impl Into<Self>) -> Bool<B> {
196        self.compare(CompareOp::Ne, other)
197    }
198    /// `self < other`.
199    pub fn lt(self, other: impl Into<Self>) -> Bool<B> {
200        self.compare(CompareOp::Lt, other)
201    }
202    /// `self <= other`.
203    pub fn le(self, other: impl Into<Self>) -> Bool<B> {
204        self.compare(CompareOp::Le, other)
205    }
206    /// `self > other`.
207    pub fn gt(self, other: impl Into<Self>) -> Bool<B> {
208        self.compare(CompareOp::Gt, other)
209    }
210    /// `self >= other`.
211    pub fn ge(self, other: impl Into<Self>) -> Bool<B> {
212        self.compare(CompareOp::Ge, other)
213    }
214
215    /// The maximum, propagating NaN (logical or for booleans).
216    pub fn max(self, other: impl Into<Self>) -> Self {
217        self.binary(BinaryOp::Max, other)
218    }
219    /// The minimum, propagating NaN (logical and for booleans).
220    pub fn min(self, other: impl Into<Self>) -> Self {
221        self.binary(BinaryOp::Min, other)
222    }
223
224    /// Converts to another element type, as `lax.convert_element_type`.
225    pub fn cast<U: Element>(self) -> Scalar<B, U> {
226        Scalar(B::cast::<T, U>(self.0))
227    }
228
229    /// Reinterprets the bits as another type of the same size.
230    pub fn bitcast<U: Element>(self) -> Scalar<B, U> {
231        Scalar(B::bitcast::<T, U>(self.0))
232    }
233
234    /// The value as an array of rank 0.
235    pub fn to_array(self) -> Array<B, T> {
236        Array(B::to_array::<T>(self.0))
237    }
238}
239
240impl<T: Element> Scalar<Native, T> {
241    /// Returns the value.
242    pub fn value(self) -> T {
243        self.0
244    }
245}
246
247impl<B: Backend, T: Numeric> Scalar<B, T> {
248    /// `|x|` (signed integers wrap around; unsigned integers are returned
249    /// unchanged; the magnitude of a complex number is real).
250    pub fn abs(self) -> Scalar<B, T::Real> {
251        Scalar(B::to_real::<T>(ToReal::Abs, self.0))
252    }
253    /// -1, 0, or 1 (`x / |x|` for complex numbers).
254    pub fn sign(self) -> Self {
255        self.unary(UnaryOp::Sign)
256    }
257    /// `x * x`.
258    pub fn square(self) -> Self {
259        self.unary(UnaryOp::Square)
260    }
261    /// `x^y` for a static integer `y` (`lax.integer_pow`).
262    pub fn integer_pow(self, y: i32) -> Self {
263        Scalar(B::integer_pow::<T>(self.0, y))
264    }
265}
266
267impl<B: Backend, T: Num> Scalar<B, T> {
268    /// Clamps to `[lo, hi]`, propagating NaN.
269    pub fn clamp(self, lo: impl Into<Self>, hi: impl Into<Self>) -> Self {
270        self.max(lo).min(hi)
271    }
272}
273
274impl<B: Backend, T: ComplexFloat> Scalar<B, T> {
275    /// A complex number from its real and imaginary parts (`lax.complex`).
276    pub fn complex(re: impl Into<Scalar<B, T::Real>>, im: impl Into<Scalar<B, T::Real>>) -> Self {
277        Scalar(B::complex::<T>(re.into().0, im.into().0))
278    }
279    /// The real part.
280    pub fn real(self) -> Scalar<B, T::Real> {
281        Scalar(B::to_real::<T>(ToReal::Real, self.0))
282    }
283    /// The imaginary part.
284    pub fn imag(self) -> Scalar<B, T::Real> {
285        Scalar(B::to_real::<T>(ToReal::Imag, self.0))
286    }
287    /// The complex conjugate.
288    pub fn conj(self) -> Self {
289        Scalar(B::conj::<T>(self.0))
290    }
291    /// The argument (`atan2(imag, real)`, as `jnp.angle`).
292    pub fn angle(self) -> Scalar<B, T::Real> {
293        self.imag().atan2(self.real())
294    }
295}
296
297impl<B: Backend, T: ComplexFloat> Array<B, T> {
298    /// Complex numbers from their real and imaginary parts (`lax.complex`;
299    /// the shapes must be equal).
300    #[track_caller]
301    pub fn complex(re: &Array<B, T::Real>, im: &Array<B, T::Real>) -> Self {
302        Array(B::a_complex::<T>(&re.0, &im.0))
303    }
304    /// The real parts.
305    pub fn real(&self) -> Array<B, T::Real> {
306        Array(B::a_to_real::<T>(ToReal::Real, &self.0))
307    }
308    /// The imaginary parts.
309    pub fn imag(&self) -> Array<B, T::Real> {
310        Array(B::a_to_real::<T>(ToReal::Imag, &self.0))
311    }
312    /// The complex conjugates.
313    pub fn conj(&self) -> Self {
314        Array(B::a_conj::<T>(&self.0))
315    }
316    /// The arguments (`atan2(imag, real)`, as `jnp.angle`).
317    pub fn angle(&self) -> Array<B, T::Real> {
318        crate::jnp::arctan2(self.imag(), self.real())
319    }
320}
321
322impl<B: Backend, T: Numeric> Array<B, T> {
323    /// `|x|` (signed integers wrap around; unsigned integers are returned
324    /// unchanged; the magnitude of a complex number is real).
325    pub fn abs(&self) -> Array<B, T::Real> {
326        Array(B::a_to_real::<T>(ToReal::Abs, &self.0))
327    }
328    /// -1, 0, or 1 (`x / |x|` for complex numbers).
329    pub fn sign(&self) -> Self {
330        self.unary(UnaryOp::Sign)
331    }
332    /// `x * x`.
333    pub fn square(&self) -> Self {
334        self.unary(UnaryOp::Square)
335    }
336    /// `x^y` for a static integer `y` (`lax.integer_pow`).
337    pub fn integer_pow(&self, y: i32) -> Self {
338        Array(B::a_integer_pow::<T>(&self.0, y))
339    }
340}
341
342macro_rules! inexact_methods {
343    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {
344        impl<B: Backend, T: Inexact> Scalar<B, T> {
345            $($(#[$m])* pub fn $name(self) -> Self { self.unary(UnaryOp::$op) })*
346
347            /// `self^y`.
348            pub fn pow(self, y: impl Into<Self>) -> Self {
349                self.binary(BinaryOp::Pow, y)
350            }
351        }
352
353        impl<B: Backend, T: Inexact> Array<B, T> {
354            $($(#[$m])* pub fn $name(&self) -> Self { self.unary(UnaryOp::$op) })*
355        }
356    };
357}
358
359inexact_methods! {
360    /// `e^x`.
361    exp => Exp;
362    /// `e^x - 1`.
363    expm1 => Expm1;
364    /// Natural logarithm (the principal value for complex numbers).
365    ln => Log;
366    /// `log(1 + x)`.
367    ln_1p => Log1p;
368    /// Square root (the principal value for complex numbers).
369    sqrt => Sqrt;
370    /// `1 / sqrt(x)`.
371    rsqrt => Rsqrt;
372    /// Sine.
373    sin => Sin;
374    /// Cosine.
375    cos => Cos;
376    /// Tangent.
377    tan => Tan;
378    /// Hyperbolic tangent.
379    tanh => Tanh;
380    /// The logistic sigmoid.
381    logistic => Logistic;
382}
383
384macro_rules! float_methods {
385    ($($(#[$m:meta])* $name:ident => $op:ident;)*) => {
386        impl<B: Backend, T: Float> Scalar<B, T> {
387            $($(#[$m])* pub fn $name(self) -> Self { self.unary(UnaryOp::$op) })*
388
389            /// `atan2(self, x)`.
390            pub fn atan2(self, x: impl Into<Self>) -> Self {
391                self.binary(BinaryOp::Atan2, x)
392            }
393            /// Whether the value is neither infinite nor NaN.
394            pub fn is_finite(self) -> Bool<B> {
395                Scalar(B::is_finite::<T>(self.0))
396            }
397        }
398
399        impl<B: Backend, T: Float> Array<B, T> {
400            $($(#[$m])* pub fn $name(&self) -> Self { self.unary(UnaryOp::$op) })*
401
402            /// Whether each element is neither infinite nor NaN.
403            pub fn is_finite(&self) -> Array<B, bool> {
404                Array(B::a_is_finite::<T>(&self.0))
405            }
406        }
407    };
408}
409
410float_methods! {
411    /// Round toward negative infinity.
412    floor => Floor;
413    /// Round toward positive infinity.
414    ceil => Ceil;
415    /// Round to the nearest integer, halfway cases away from zero.
416    round => Round;
417    /// Round to the nearest integer, halfway cases to even.
418    round_even => RoundEven;
419    /// Cube root.
420    cbrt => Cbrt;
421    /// The inverse error function.
422    erf_inv => ErfInv;
423    /// The logarithm of the absolute value of the gamma function.
424    lgamma => Lgamma;
425    /// The digamma function.
426    digamma => Digamma;
427    /// The error function.
428    erf => Erf;
429    /// The complementary error function.
430    erfc => Erfc;
431}
432
433macro_rules! scalar_binop {
434    ($($tr:ident $f:ident $op:ident $bound:ident;)*) => {$(
435        impl<B: Backend, T: $bound> ops::$tr for Scalar<B, T> {
436            type Output = Self;
437            fn $f(self, rhs: Self) -> Self {
438                self.binary(BinaryOp::$op, rhs)
439            }
440        }
441        impl<B: Backend, T: $bound> ops::$tr<T> for Scalar<B, T> {
442            type Output = Self;
443            fn $f(self, rhs: T) -> Self {
444                self.binary(BinaryOp::$op, rhs)
445            }
446        }
447    )*};
448}
449
450scalar_binop! {
451    Add add Add Numeric;
452    Sub sub Sub Numeric;
453    Mul mul Mul Numeric;
454    Div div Div Numeric;
455    Rem rem Rem Num;
456    BitAnd bitand And Element;
457    BitOr bitor Or Element;
458    BitXor bitxor Xor Element;
459}
460
461macro_rules! scalar_lhs_literal {
462    ($($t:ty)*) => {$(
463        impl<B: Backend> ops::Add<Scalar<B, $t>> for $t {
464            type Output = Scalar<B, $t>;
465            fn add(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) + rhs }
466        }
467        impl<B: Backend> ops::Sub<Scalar<B, $t>> for $t {
468            type Output = Scalar<B, $t>;
469            fn sub(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) - rhs }
470        }
471        impl<B: Backend> ops::Mul<Scalar<B, $t>> for $t {
472            type Output = Scalar<B, $t>;
473            fn mul(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) * rhs }
474        }
475        impl<B: Backend> ops::Div<Scalar<B, $t>> for $t {
476            type Output = Scalar<B, $t>;
477            fn div(self, rhs: Scalar<B, $t>) -> Scalar<B, $t> { Scalar::new(self) / rhs }
478        }
479    )*};
480}
481
482scalar_lhs_literal!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64 c64 c128);
483
484impl<B: Backend, T: Numeric> ops::Neg for Scalar<B, T> {
485    type Output = Self;
486    fn neg(self) -> Self {
487        self.unary(UnaryOp::Neg)
488    }
489}
490
491impl<B: Backend, T: Element> ops::Not for Scalar<B, T> {
492    type Output = Self;
493    fn not(self) -> Self {
494        self.unary(UnaryOp::Not)
495    }
496}
497
498impl<B: Backend, T: Int> ops::Shl for Scalar<B, T> {
499    type Output = Self;
500    fn shl(self, rhs: Self) -> Self {
501        self.binary(BinaryOp::ShiftLeft, rhs)
502    }
503}
504
505impl<B: Backend, T: Int> ops::Shr for Scalar<B, T> {
506    type Output = Self;
507    /// A logical shift for unsigned types and an arithmetic shift for signed
508    /// types, as Rust's `>>`.
509    fn shr(self, rhs: Self) -> Self {
510        let op = if T::DTYPE.kind() == ruxla_ir::DTypeKind::UnsignedInt {
511            BinaryOp::ShiftRightLogical
512        } else {
513            BinaryOp::ShiftRightArithmetic
514        };
515        self.binary(op, rhs)
516    }
517}
518
519impl<B: Backend, T: Int> ops::Shl<T> for Scalar<B, T> {
520    type Output = Self;
521    fn shl(self, rhs: T) -> Self {
522        self << Scalar::new(rhs)
523    }
524}
525
526impl<B: Backend, T: Int> ops::Shr<T> for Scalar<B, T> {
527    type Output = Self;
528    fn shr(self, rhs: T) -> Self {
529        self >> Scalar::new(rhs)
530    }
531}
532
533/// An array of element type `T` on backend `B`, with a shape known at run
534/// time (and fixed within a traced program).
535///
536/// On `Native` it holds shared elements, so `clone` is cheap; on `Trace` it
537/// is a traced value.
538#[repr(transparent)]
539pub struct Array<B: Backend, T: Element>(pub(crate) B::Array<T>);
540
541impl<B: Backend, T: Element> Clone for Array<B, T> {
542    #[inline]
543    fn clone(&self) -> Self {
544        Array(self.0.clone())
545    }
546}
547
548impl<B: Backend, T: Element> fmt::Debug for Array<B, T> {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        write!(f, "Array<{}>({:?})", T::DTYPE, self.0)
551    }
552}
553
554impl<B: Backend, T: Element> Array<B, T> {
555    /// A constant array from its elements in row-major order.
556    ///
557    /// # Panics
558    ///
559    /// Panics if the number of elements does not match the shape.
560    #[track_caller]
561    pub fn from_vec(data: Vec<T>, shape: impl Into<Shape>) -> Self {
562        Array(B::constant_owned(NativeArray::new(data, shape)))
563    }
564
565    /// A constant array from a copy of its elements in row-major order
566    /// (like [`Array::from_vec`], without a `Vec`).
567    ///
568    /// # Examples
569    ///
570    /// ```
571    /// use ruxla_core::{Array, I32, Native};
572    ///
573    /// let table = Array::<Native, i32>::from_slice(&[1, 0, 3, 2], [4]);
574    /// assert_eq!(table.get(I32::new(2)).value(), 3);
575    /// ```
576    ///
577    /// # Panics
578    ///
579    /// Panics if the number of elements does not match the shape.
580    #[track_caller]
581    #[inline]
582    pub fn from_slice(data: &[T], shape: impl Into<Shape>) -> Self {
583        Array(B::constant_owned(NativeArray::from_slice(data, shape)))
584    }
585
586    /// A constant array.
587    pub fn constant(x: &NativeArray<T>) -> Self {
588        Array(B::constant(x))
589    }
590
591    /// Wraps a backend value.
592    pub fn from_repr(r: B::Array<T>) -> Self {
593        Array(r)
594    }
595
596    /// Returns the backend value.
597    pub fn repr(&self) -> &B::Array<T> {
598        &self.0
599    }
600
601    /// Views arrays as their backend representations.
602    pub(crate) fn reprs(xs: &[Self]) -> &[B::Array<T>] {
603        // SAFETY: `Array` is `#[repr(transparent)]` over `B::Array<T>`, so a
604        // slice of one has the layout of a slice of the other.
605        unsafe { std::slice::from_raw_parts(xs.as_ptr().cast::<B::Array<T>>(), xs.len()) }
606    }
607
608    /// Returns the shape.
609    pub fn shape(&self) -> Shape {
610        B::shape::<T>(&self.0)
611    }
612
613    /// Returns the number of dimensions.
614    #[inline]
615    pub fn ndim(&self) -> usize {
616        B::rank::<T>(&self.0)
617    }
618
619    /// Returns the number of elements.
620    #[inline]
621    pub fn size(&self) -> usize {
622        match B::dims(&self.0) {
623            Some(dims) => dims.iter().product(),
624            None => self.shape().size(),
625        }
626    }
627
628    /// The only element of an array of rank 0.
629    ///
630    /// # Panics
631    ///
632    /// Panics if the rank is not 0.
633    #[track_caller]
634    pub fn to_scalar(&self) -> Scalar<B, T> {
635        Scalar(B::to_scalar::<T>(&self.0))
636    }
637
638    /// Converts to another element type.
639    pub fn cast<U: Element>(&self) -> Array<B, U> {
640        Array(B::a_cast::<T, U>(&self.0))
641    }
642
643    /// Changes the shape, keeping the elements in row-major order.
644    ///
645    /// # Panics
646    ///
647    /// Panics if the sizes differ.
648    #[track_caller]
649    pub fn reshape(&self, shape: impl Into<Shape>) -> Self {
650        Array(B::reshape::<T>(&self.0, &shape.into()))
651    }
652
653    /// Permutes the dimensions: dimension `i` of the result is dimension
654    /// `perm[i]` of `self`.
655    #[track_caller]
656    pub fn transpose(&self, perm: &[usize]) -> Self {
657        Array(B::transpose::<T>(&self.0, perm))
658    }
659
660    /// Broadcasts to `shape` with NumPy's rules.
661    ///
662    /// # Panics
663    ///
664    /// Panics if the shapes are not compatible.
665    #[track_caller]
666    pub fn broadcast_to(&self, shape: impl Into<Shape>) -> Self {
667        let shape = shape.into();
668        let s = self.shape();
669        if s == shape {
670            return self.clone();
671        }
672        assert!(
673            s.rank() <= shape.rank(),
674            "cannot broadcast [{s}] to [{shape}]"
675        );
676        let offset = shape.rank() - s.rank();
677        let dims: Vec<usize> = (0..s.rank()).map(|i| i + offset).collect();
678        for (i, &d) in dims.iter().enumerate() {
679            assert!(
680                s[i] == 1 || s[i] == shape[d],
681                "cannot broadcast [{s}] to [{shape}]"
682            );
683        }
684        Array(B::broadcast_in_dim::<T>(&self.0, &shape, &dims))
685    }
686
687    pub(crate) fn unary(&self, op: UnaryOp) -> Self {
688        Array(B::a_unary::<T>(op, &self.0))
689    }
690
691    /// [`Self::unary`] of an owned array: written over its elements where
692    /// they are not shared.
693    pub(crate) fn into_unary(mut self, op: UnaryOp) -> Self {
694        if B::FAST_PATHS && B::a_unary_assign::<T>(op, &mut self.0) {
695            return self;
696        }
697        self.unary(op)
698    }
699
700    /// Sums over `axes` (`lax.reduce_sum`; integers wrap around).
701    #[track_caller]
702    pub fn reduce_sum(&self, axes: &[usize]) -> Self {
703        Array(B::reduce::<T>(ReduceOp::Sum, &self.0, axes))
704    }
705
706    /// The maximum over `axes`, propagating NaN (`lax.reduce_max`).
707    #[track_caller]
708    pub fn reduce_max(&self, axes: &[usize]) -> Self {
709        Array(B::reduce::<T>(ReduceOp::Max, &self.0, axes))
710    }
711
712    /// The minimum over `axes`, propagating NaN (`lax.reduce_min`).
713    #[track_caller]
714    pub fn reduce_min(&self, axes: &[usize]) -> Self {
715        Array(B::reduce::<T>(ReduceOp::Min, &self.0, axes))
716    }
717}
718
719impl<T: Element> Array<Native, T> {
720    /// Returns the elements in row-major order.
721    pub fn to_vec(&self) -> Vec<T> {
722        self.0.data().to_vec()
723    }
724
725    /// Returns the native array.
726    pub fn native(&self) -> &NativeArray<T> {
727        &self.0
728    }
729}
730
731/// Returns the shape that two shapes broadcast to, with NumPy's rules.
732#[track_caller]
733pub(crate) fn broadcast_shapes(a: &Shape, b: &Shape) -> Shape {
734    let r = a.rank().max(b.rank());
735    let dim = |s: &Shape, i: usize| {
736        if i + s.rank() < r {
737            1
738        } else {
739            s[i + s.rank() - r]
740        }
741    };
742    if a == b {
743        return a.clone();
744    }
745    (0..r)
746        .map(|i| {
747            let (x, y) = (dim(a, i), dim(b, i));
748            assert!(
749                x == y || x == 1 || y == 1,
750                "shapes [{a}] and [{b}] do not broadcast"
751            );
752            x.max(y)
753        })
754        .collect()
755}
756
757/// Applies a binary operation with NumPy's broadcasting.
758#[track_caller]
759pub(crate) fn broadcast_binary<B: Backend, T: Element>(
760    op: BinaryOp,
761    a: &Array<B, T>,
762    b: &Array<B, T>,
763) -> Array<B, T> {
764    if let Some(r) = B::a_binary_broadcast::<T>(op, &a.0, &b.0) {
765        return Array(r);
766    }
767    let s = broadcast_shapes(&a.shape(), &b.shape());
768    Array(B::a_binary::<T>(
769        op,
770        &a.broadcast_to(s.clone()).0,
771        &b.broadcast_to(s).0,
772    ))
773}
774
775/// Applies a comparison with NumPy's broadcasting.
776#[track_caller]
777pub(crate) fn broadcast_compare<B: Backend, T: Element>(
778    op: CompareOp,
779    a: &Array<B, T>,
780    b: &Array<B, T>,
781) -> Array<B, bool> {
782    if let Some(r) = B::a_compare_broadcast::<T>(op, &a.0, &b.0) {
783        return Array(r);
784    }
785    let s = broadcast_shapes(&a.shape(), &b.shape());
786    Array(B::a_compare::<T>(
787        op,
788        &a.broadcast_to(s.clone()).0,
789        &b.broadcast_to(s).0,
790    ))
791}
792
793/// Something that can be an operand of an array operation: an array, a
794/// scalar, or a Rust value.
795pub trait ArrayLike<B: Backend, T: Element>: Sized {
796    /// Converts to an array.
797    fn into_array(self) -> Array<B, T>;
798
799    /// Calls `f` with the array, without copying a borrowed array.
800    #[inline]
801    fn with_array<R>(self, f: impl FnOnce(&Array<B, T>) -> R) -> R {
802        f(&self.into_array())
803    }
804
805    /// The value as a scalar, if it is one (for fast paths).
806    #[doc(hidden)]
807    #[inline]
808    fn as_scalar(&self) -> Option<Scalar<B, T>> {
809        None
810    }
811
812    /// Whether this is a borrowed array (whose elements must not be
813    /// written over).
814    #[doc(hidden)]
815    #[inline]
816    fn is_borrowed(&self) -> bool {
817        false
818    }
819}
820
821impl<B: Backend, T: Element> ArrayLike<B, T> for Array<B, T> {
822    fn into_array(self) -> Array<B, T> {
823        self
824    }
825}
826impl<B: Backend, T: Element> ArrayLike<B, T> for &Array<B, T> {
827    fn into_array(self) -> Array<B, T> {
828        self.clone()
829    }
830    #[inline]
831    fn with_array<R>(self, f: impl FnOnce(&Array<B, T>) -> R) -> R {
832        f(self)
833    }
834    #[inline]
835    fn is_borrowed(&self) -> bool {
836        true
837    }
838}
839impl<B: Backend, T: Element> ArrayLike<B, T> for Scalar<B, T> {
840    #[inline]
841    fn into_array(self) -> Array<B, T> {
842        self.to_array()
843    }
844    #[inline]
845    fn as_scalar(&self) -> Option<Scalar<B, T>> {
846        Some(*self)
847    }
848}
849impl<B: Backend, T: Element> ArrayLike<B, T> for T {
850    #[inline]
851    fn into_array(self) -> Array<B, T> {
852        Scalar::<B, T>::new(self).to_array()
853    }
854    #[inline]
855    fn as_scalar(&self) -> Option<Scalar<B, T>> {
856        Some(Scalar::new(*self))
857    }
858}
859
860macro_rules! array_binop {
861    ($($tr:ident $f:ident $op:ident $bound:ident;)*) => {$(
862        impl<B: Backend, T: $bound, R: ArrayLike<B, T>> ops::$tr<R> for Array<B, T> {
863            type Output = Array<B, T>;
864            #[track_caller]
865            fn $f(mut self, rhs: R) -> Array<B, T> {
866                rhs.with_array(|r| {
867                    // An array that is not shared is written over.
868                    if B::FAST_PATHS && B::a_binary_assign::<T>(BinaryOp::$op, &mut self.0, &r.0) {
869                        return self;
870                    }
871                    broadcast_binary(BinaryOp::$op, &self, r)
872                })
873            }
874        }
875        impl<B: Backend, T: $bound, R: ArrayLike<B, T>> ops::$tr<R> for &Array<B, T> {
876            type Output = Array<B, T>;
877            #[track_caller]
878            fn $f(self, rhs: R) -> Array<B, T> {
879                if B::FAST_PATHS && BinaryOp::$op.is_commutative() && !rhs.is_borrowed() {
880                    // A commutative operation writes over a new right
881                    // operand that is not shared.
882                    let mut r = rhs.into_array();
883                    if B::a_binary_assign::<T>(BinaryOp::$op, &mut r.0, &self.0) {
884                        return r;
885                    }
886                    return broadcast_binary(BinaryOp::$op, self, &r);
887                }
888                rhs.with_array(|r| broadcast_binary(BinaryOp::$op, self, r))
889            }
890        }
891        impl<B: Backend, T: $bound> ops::$tr<Array<B, T>> for Scalar<B, T> {
892            type Output = Array<B, T>;
893            #[track_caller]
894            fn $f(self, rhs: Array<B, T>) -> Array<B, T> {
895                broadcast_binary(BinaryOp::$op, &self.to_array(), &rhs)
896            }
897        }
898        impl<B: Backend, T: $bound> ops::$tr<&Array<B, T>> for Scalar<B, T> {
899            type Output = Array<B, T>;
900            #[track_caller]
901            fn $f(self, rhs: &Array<B, T>) -> Array<B, T> {
902                broadcast_binary(BinaryOp::$op, &self.to_array(), rhs)
903            }
904        }
905    )*};
906}
907
908array_binop! {
909    Add add Add Numeric;
910    Sub sub Sub Numeric;
911    Mul mul Mul Numeric;
912    Div div Div Numeric;
913    Rem rem Rem Num;
914    BitAnd bitand And Element;
915    BitOr bitor Or Element;
916    BitXor bitxor Xor Element;
917}
918
919macro_rules! array_lhs_literal {
920    ($($t:ty)*) => {$(
921        impl<B: Backend> ops::Add<Array<B, $t>> for $t {
922            type Output = Array<B, $t>;
923            fn add(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Add, &self.into_array(), &rhs) }
924        }
925        impl<B: Backend> ops::Sub<Array<B, $t>> for $t {
926            type Output = Array<B, $t>;
927            fn sub(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Sub, &self.into_array(), &rhs) }
928        }
929        impl<B: Backend> ops::Mul<Array<B, $t>> for $t {
930            type Output = Array<B, $t>;
931            fn mul(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Mul, &self.into_array(), &rhs) }
932        }
933        impl<B: Backend> ops::Div<Array<B, $t>> for $t {
934            type Output = Array<B, $t>;
935            fn div(self, rhs: Array<B, $t>) -> Array<B, $t> { broadcast_binary(BinaryOp::Div, &self.into_array(), &rhs) }
936        }
937    )*};
938}
939
940array_lhs_literal!(i8 i16 i32 i64 u8 u16 u32 u64 f16 bf16 f32 f64 c64 c128);
941
942impl<B: Backend, T: Numeric> ops::Neg for Array<B, T> {
943    type Output = Self;
944    fn neg(self) -> Self {
945        self.into_unary(UnaryOp::Neg)
946    }
947}
948
949impl<B: Backend, T: Numeric> ops::Neg for &Array<B, T> {
950    type Output = Array<B, T>;
951    fn neg(self) -> Array<B, T> {
952        self.unary(UnaryOp::Neg)
953    }
954}
955
956impl<B: Backend, T: Element> ops::Not for Array<B, T> {
957    type Output = Self;
958    fn not(self) -> Self {
959        self.into_unary(UnaryOp::Not)
960    }
961}
962
963impl<B: Backend, T: Element> ops::Not for &Array<B, T> {
964    type Output = Array<B, T>;
965    fn not(self) -> Array<B, T> {
966        self.unary(UnaryOp::Not)
967    }
968}
969
970impl<B: Backend, T: Element> Array<B, T> {
971    /// `self == other`, elementwise with broadcasting.
972    #[track_caller]
973    pub fn eq(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
974        broadcast_compare(CompareOp::Eq, self, &other.into_array())
975    }
976    /// `self != other`.
977    #[track_caller]
978    pub fn ne(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
979        broadcast_compare(CompareOp::Ne, self, &other.into_array())
980    }
981    /// `self < other`.
982    #[track_caller]
983    pub fn lt(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
984        broadcast_compare(CompareOp::Lt, self, &other.into_array())
985    }
986    /// `self <= other`.
987    #[track_caller]
988    pub fn le(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
989        broadcast_compare(CompareOp::Le, self, &other.into_array())
990    }
991    /// `self > other`.
992    #[track_caller]
993    pub fn gt(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
994        broadcast_compare(CompareOp::Gt, self, &other.into_array())
995    }
996    /// `self >= other`.
997    #[track_caller]
998    pub fn ge(&self, other: impl ArrayLike<B, T>) -> Array<B, bool> {
999        broadcast_compare(CompareOp::Ge, self, &other.into_array())
1000    }
1001}