Skip to main content

yscv_tensor/ops/
elementwise.rs

1//! Element-wise tensor ops: binary (broadcasting) + unary math/trig.
2
3use super::super::aligned::AlignedVec;
4use super::super::error::TensorError;
5use super::super::simd;
6use super::super::tensor::Tensor;
7use super::fast_atan2_scalar;
8
9impl Tensor {
10    // ── Binary elementwise with broadcasting ────────────────────────────
11
12    /// Element-wise addition with NumPy-style broadcasting.
13    pub fn add(&self, rhs: &Self) -> Result<Self, TensorError> {
14        if self.shape() == rhs.shape() {
15            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Add);
16        }
17        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Add) {
18            return result;
19        }
20        self.binary_broadcast_op(rhs, |l, r| l + r)
21    }
22
23    /// Element-wise subtraction with NumPy-style broadcasting.
24    pub fn sub(&self, rhs: &Self) -> Result<Self, TensorError> {
25        if self.shape() == rhs.shape() {
26            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Sub);
27        }
28        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Sub) {
29            return result;
30        }
31        self.binary_broadcast_op(rhs, |l, r| l - r)
32    }
33
34    /// Element-wise multiplication with NumPy-style broadcasting.
35    pub fn mul(&self, rhs: &Self) -> Result<Self, TensorError> {
36        if self.shape() == rhs.shape() {
37            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Mul);
38        }
39        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Mul) {
40            return result;
41        }
42        self.binary_broadcast_op(rhs, |l, r| l * r)
43    }
44
45    /// Element-wise division with NumPy-style broadcasting.
46    pub fn div(&self, rhs: &Self) -> Result<Self, TensorError> {
47        if self.shape() == rhs.shape() {
48            return self.binary_same_shape_simd(rhs, simd::BinaryKind::Div);
49        }
50        if let Some(result) = self.binary_broadcast_lastdim_simd(rhs, simd::BinaryKind::Div) {
51            return result;
52        }
53        self.binary_broadcast_op(rhs, |l, r| l / r)
54    }
55
56    /// Element-wise power with NumPy-style broadcasting.
57    ///
58    /// Fast paths:
59    /// - Constant exponent 2.0 → `mul(x, x)` (SIMD-accelerated).
60    /// - Constant exponent 0.5 → `sqrt(x)` (SIMD-accelerated).
61    /// - Same-shape general case → SIMD `exp(exp * ln(base))`.
62    #[allow(unsafe_code)]
63    pub fn pow(&self, rhs: &Self) -> Result<Self, TensorError> {
64        // Fast path: constant exponent (O(1) check instead of O(N) scan).
65        // A single-element tensor or a tensor whose total size is 1 (broadcast scalar)
66        // is always constant.  For same-shape tensors we skip the all-equal scan
67        // entirely — the per-element SIMD path handles them efficiently.
68        let rhs_total: usize = rhs.shape().iter().product();
69        if rhs_total == 1 {
70            let exp_val = rhs.data()[0];
71            if exp_val == 2.0 {
72                return self.mul(self);
73            }
74            if exp_val == 0.5 {
75                return Ok(self.sqrt());
76            }
77            if exp_val == 1.0 {
78                return Ok(self.clone());
79            }
80            if exp_val == 0.0 {
81                return Tensor::ones(self.shape().to_vec());
82            }
83            if exp_val == -1.0 {
84                return Ok(self.reciprocal());
85            }
86        }
87        // Same-shape SIMD path: pow(base, exp) = exp(exp * ln(base))
88        if self.shape() == rhs.shape() {
89            return self.pow_simd(rhs);
90        }
91        self.binary_broadcast_op(rhs, |l, r| l.powf(r))
92    }
93
94    /// SIMD-accelerated pow for same-shape tensors via exp(exp * ln(base)).
95    #[allow(unsafe_code)]
96    fn pow_simd(&self, rhs: &Self) -> Result<Self, TensorError> {
97        let len = self.len();
98        // Compute ln(base)
99        let mut ln_buf = AlignedVec::<f32>::uninitialized(len);
100        simd::ln_dispatch(self.data(), &mut ln_buf);
101        // Multiply by exponent: exp_val * ln(base)
102        let mut prod_buf = AlignedVec::<f32>::uninitialized(len);
103        simd::binary_dispatch(&ln_buf, rhs.data(), &mut prod_buf, simd::BinaryKind::Mul);
104        // Compute exp(exp_val * ln(base))
105        let mut out = AlignedVec::<f32>::uninitialized(len);
106        simd::exp_dispatch(&prod_buf, &mut out);
107        Ok(Tensor::from_raw_parts(self.shape(), self.strides(), out))
108    }
109
110    /// Element-wise atan2(self, other), with broadcasting.
111    ///
112    /// Same-shape case uses a SIMD-friendly polynomial approximation of atan
113    /// with quadrant correction, avoiding scalar `f32::atan2`.
114    #[allow(unsafe_code)]
115    pub fn atan2(&self, rhs: &Self) -> Result<Self, TensorError> {
116        if self.shape() == rhs.shape() {
117            return self.atan2_fast(rhs);
118        }
119        self.binary_broadcast_op(rhs, f32::atan2)
120    }
121
122    /// Vectorized atan2 for same-shape tensors. Uses Cephes-style range
123    /// reduction to [0, tan(pi/12)] then a polynomial approximation,
124    /// giving < 1e-6 max error across all quadrants.
125    #[allow(unsafe_code)]
126    fn atan2_fast(&self, rhs: &Self) -> Result<Self, TensorError> {
127        let y_data = self.data();
128        let x_data = rhs.data();
129        let len = self.len();
130        let mut out = AlignedVec::<f32>::uninitialized(len);
131
132        // Process in chunks of 4 for ILP (instruction-level parallelism).
133        // Each call to the scalar fast path avoids the overhead of the
134        // generic broadcasting machinery.
135        let mut i = 0;
136        while i + 4 <= len {
137            out[i] = fast_atan2_scalar(y_data[i], x_data[i]);
138            out[i + 1] = fast_atan2_scalar(y_data[i + 1], x_data[i + 1]);
139            out[i + 2] = fast_atan2_scalar(y_data[i + 2], x_data[i + 2]);
140            out[i + 3] = fast_atan2_scalar(y_data[i + 3], x_data[i + 3]);
141            i += 4;
142        }
143        while i < len {
144            out[i] = fast_atan2_scalar(y_data[i], x_data[i]);
145            i += 1;
146        }
147
148        Ok(Tensor::from_raw_parts(self.shape(), self.strides(), out))
149    }
150
151    /// Element-wise minimum with NumPy-style broadcasting.
152    pub fn minimum(&self, rhs: &Self) -> Result<Self, TensorError> {
153        if self.shape() == rhs.shape() {
154            return self.binary_same_shape(rhs, f32::min);
155        }
156        self.binary_broadcast_op(rhs, f32::min)
157    }
158
159    /// Element-wise maximum with NumPy-style broadcasting.
160    pub fn maximum(&self, rhs: &Self) -> Result<Self, TensorError> {
161        if self.shape() == rhs.shape() {
162            return self.binary_same_shape(rhs, f32::max);
163        }
164        self.binary_broadcast_op(rhs, f32::max)
165    }
166
167    // ── Unary elementwise ───────────────────────────────────────────────
168
169    /// Element-wise negation.
170    pub fn neg(&self) -> Self {
171        self.unary_simd_op(simd::UnaryKind::Neg)
172    }
173
174    /// Element-wise absolute value.
175    pub fn abs(&self) -> Self {
176        self.unary_simd_op(simd::UnaryKind::Abs)
177    }
178
179    /// Element-wise natural exponential.
180    #[allow(unsafe_code)]
181    pub fn exp(&self) -> Self {
182        let len = self.len();
183        // SAFETY: `uninitialized` allocates without zeroing.  `exp_dispatch`
184        // writes every element before anything reads from `out`.
185        let mut out = AlignedVec::<f32>::uninitialized(len);
186        simd::exp_dispatch(self.data(), &mut out);
187        Tensor::from_raw_parts(self.shape(), self.strides(), out)
188    }
189
190    /// Element-wise natural logarithm.
191    #[allow(unsafe_code)]
192    pub fn ln(&self) -> Self {
193        let len = self.len();
194        // SAFETY: `uninitialized` allocates without zeroing.  `ln_dispatch`
195        // writes every element before we ever read from `out`.
196        let mut out = AlignedVec::<f32>::uninitialized(len);
197        simd::ln_dispatch(self.data(), &mut out);
198        Tensor::from_raw_parts(self.shape(), self.strides(), out)
199    }
200
201    /// Element-wise square root.
202    pub fn sqrt(&self) -> Self {
203        self.unary_simd_op(simd::UnaryKind::Sqrt)
204    }
205
206    /// Element-wise reciprocal (`1 / x`).
207    pub fn reciprocal(&self) -> Self {
208        self.unary_simd_op(simd::UnaryKind::Recip)
209    }
210
211    /// Element-wise sign (`-1`, `0`, or `1`).
212    pub fn sign(&self) -> Self {
213        self.unary_simd_op(simd::UnaryKind::Sign)
214    }
215
216    /// Element-wise floor.
217    pub fn floor(&self) -> Self {
218        self.unary_simd_op(simd::UnaryKind::Floor)
219    }
220
221    /// Element-wise ceil.
222    pub fn ceil(&self) -> Self {
223        self.unary_simd_op(simd::UnaryKind::Ceil)
224    }
225
226    /// Element-wise round.
227    pub fn round(&self) -> Self {
228        self.unary_simd_op(simd::UnaryKind::Round)
229    }
230
231    /// Element-wise sine (SIMD-accelerated polynomial approximation).
232    #[allow(unsafe_code)]
233    pub fn sin(&self) -> Self {
234        let len = self.len();
235        let mut out = AlignedVec::<f32>::uninitialized(len);
236        simd::sin_dispatch(self.data(), &mut out);
237        Tensor::from_raw_parts(self.shape(), self.strides(), out)
238    }
239
240    /// Element-wise cosine (SIMD-accelerated polynomial approximation).
241    #[allow(unsafe_code)]
242    pub fn cos(&self) -> Self {
243        let len = self.len();
244        let mut out = AlignedVec::<f32>::uninitialized(len);
245        simd::cos_dispatch(self.data(), &mut out);
246        Tensor::from_raw_parts(self.shape(), self.strides(), out)
247    }
248
249    /// Element-wise tangent (SIMD-accelerated via sin/cos).
250    #[allow(unsafe_code)]
251    pub fn tan(&self) -> Self {
252        let len = self.len();
253        let mut out = AlignedVec::<f32>::uninitialized(len);
254        simd::tan_dispatch(self.data(), &mut out);
255        Tensor::from_raw_parts(self.shape(), self.strides(), out)
256    }
257
258    /// Element-wise arcsine.
259    pub fn asin(&self) -> Self {
260        self.unary_op(f32::asin)
261    }
262
263    /// Element-wise arccosine.
264    pub fn acos(&self) -> Self {
265        self.unary_op(f32::acos)
266    }
267
268    /// Element-wise arctangent.
269    pub fn atan(&self) -> Self {
270        self.unary_op(f32::atan)
271    }
272
273    /// Element-wise hyperbolic sine.
274    pub fn sinh(&self) -> Self {
275        self.unary_op(f32::sinh)
276    }
277
278    /// Element-wise hyperbolic cosine.
279    pub fn cosh(&self) -> Self {
280        self.unary_op(f32::cosh)
281    }
282
283    /// Element-wise base-2 logarithm.
284    pub fn log2(&self) -> Self {
285        self.unary_op(f32::log2)
286    }
287
288    /// Element-wise base-10 logarithm.
289    pub fn log10(&self) -> Self {
290        self.unary_op(f32::log10)
291    }
292
293    /// Convert radians to degrees.
294    pub fn degrees(&self) -> Self {
295        self.unary_op(|v| v.to_degrees())
296    }
297
298    /// Convert degrees to radians.
299    pub fn radians(&self) -> Self {
300        self.unary_op(|v| v.to_radians())
301    }
302
303    /// Clamp all elements to `[min, max]`.
304    #[allow(unsafe_code)]
305    pub fn clamp(&self, min: f32, max: f32) -> Self {
306        let len = self.len();
307        let mut out = AlignedVec::<f32>::uninitialized(len);
308        simd::clamp_dispatch(self.data(), &mut out, min, max);
309        Tensor::from_raw_parts(self.shape(), self.strides(), out)
310    }
311
312    /// Scalar multiplication (broadcast multiply by a constant).
313    pub fn scale(&self, factor: f32) -> Self {
314        self.unary_op(|v| v * factor)
315    }
316
317    /// Add a scalar to all elements.
318    pub fn add_scalar(&self, value: f32) -> Self {
319        self.unary_op(|v| v + value)
320    }
321}