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        // SAFETY: all temporary buffers are fully written before use.
100        let mut ln_buf = unsafe { AlignedVec::<f32>::uninitialized(len) };
101        simd::ln_dispatch(self.data(), &mut ln_buf);
102        // Multiply by exponent: exp_val * ln(base)
103        // SAFETY: all temporary buffers are fully written before use.
104        let mut prod_buf = unsafe { AlignedVec::<f32>::uninitialized(len) };
105        simd::binary_dispatch(&ln_buf, rhs.data(), &mut prod_buf, simd::BinaryKind::Mul);
106        // Compute exp(exp_val * ln(base))
107        // SAFETY: all output elements are written before the tensor is returned.
108        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
109        simd::exp_dispatch(&prod_buf, &mut out);
110        Ok(Tensor::from_raw_parts(self.shape(), self.strides(), out))
111    }
112
113    /// Element-wise atan2(self, other), with broadcasting.
114    ///
115    /// Same-shape case uses a SIMD-friendly polynomial approximation of atan
116    /// with quadrant correction, avoiding scalar `f32::atan2`.
117    #[allow(unsafe_code)]
118    pub fn atan2(&self, rhs: &Self) -> Result<Self, TensorError> {
119        if self.shape() == rhs.shape() {
120            return self.atan2_fast(rhs);
121        }
122        self.binary_broadcast_op(rhs, f32::atan2)
123    }
124
125    /// Vectorized atan2 for same-shape tensors. Uses Cephes-style range
126    /// reduction to [0, tan(pi/12)] then a polynomial approximation,
127    /// giving < 1e-6 max error across all quadrants.
128    #[allow(unsafe_code)]
129    fn atan2_fast(&self, rhs: &Self) -> Result<Self, TensorError> {
130        let y_data = self.data();
131        let x_data = rhs.data();
132        let len = self.len();
133        // SAFETY: all output elements are written before the tensor is returned.
134        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
135
136        // Process in chunks of 4 for ILP (instruction-level parallelism).
137        // Each call to the scalar fast path avoids the overhead of the
138        // generic broadcasting machinery.
139        let mut i = 0;
140        while i + 4 <= len {
141            out[i] = fast_atan2_scalar(y_data[i], x_data[i]);
142            out[i + 1] = fast_atan2_scalar(y_data[i + 1], x_data[i + 1]);
143            out[i + 2] = fast_atan2_scalar(y_data[i + 2], x_data[i + 2]);
144            out[i + 3] = fast_atan2_scalar(y_data[i + 3], x_data[i + 3]);
145            i += 4;
146        }
147        while i < len {
148            out[i] = fast_atan2_scalar(y_data[i], x_data[i]);
149            i += 1;
150        }
151
152        Ok(Tensor::from_raw_parts(self.shape(), self.strides(), out))
153    }
154
155    /// Element-wise minimum with NumPy-style broadcasting.
156    pub fn minimum(&self, rhs: &Self) -> Result<Self, TensorError> {
157        if self.shape() == rhs.shape() {
158            return self.binary_same_shape(rhs, f32::min);
159        }
160        self.binary_broadcast_op(rhs, f32::min)
161    }
162
163    /// Element-wise maximum with NumPy-style broadcasting.
164    pub fn maximum(&self, rhs: &Self) -> Result<Self, TensorError> {
165        if self.shape() == rhs.shape() {
166            return self.binary_same_shape(rhs, f32::max);
167        }
168        self.binary_broadcast_op(rhs, f32::max)
169    }
170
171    // ── Unary elementwise ───────────────────────────────────────────────
172
173    /// Element-wise negation.
174    pub fn neg(&self) -> Self {
175        self.unary_simd_op(simd::UnaryKind::Neg)
176    }
177
178    /// Element-wise absolute value.
179    pub fn abs(&self) -> Self {
180        self.unary_simd_op(simd::UnaryKind::Abs)
181    }
182
183    /// Element-wise natural exponential.
184    #[allow(unsafe_code)]
185    pub fn exp(&self) -> Self {
186        let len = self.len();
187        // SAFETY: `uninitialized` allocates without zeroing.  `exp_dispatch`
188        // writes every element before anything reads from `out`.
189        // SAFETY: all output elements are written before the tensor is returned.
190        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
191        simd::exp_dispatch(self.data(), &mut out);
192        Tensor::from_raw_parts(self.shape(), self.strides(), out)
193    }
194
195    /// Element-wise natural logarithm.
196    #[allow(unsafe_code)]
197    pub fn ln(&self) -> Self {
198        let len = self.len();
199        // SAFETY: `uninitialized` allocates without zeroing.  `ln_dispatch`
200        // writes every element before we ever read from `out`.
201        // SAFETY: all output elements are written before the tensor is returned.
202        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
203        simd::ln_dispatch(self.data(), &mut out);
204        Tensor::from_raw_parts(self.shape(), self.strides(), out)
205    }
206
207    /// Element-wise square root.
208    pub fn sqrt(&self) -> Self {
209        self.unary_simd_op(simd::UnaryKind::Sqrt)
210    }
211
212    /// Element-wise reciprocal (`1 / x`).
213    pub fn reciprocal(&self) -> Self {
214        self.unary_simd_op(simd::UnaryKind::Recip)
215    }
216
217    /// Element-wise sign (`-1`, `0`, or `1`).
218    pub fn sign(&self) -> Self {
219        self.unary_simd_op(simd::UnaryKind::Sign)
220    }
221
222    /// Element-wise floor.
223    pub fn floor(&self) -> Self {
224        self.unary_simd_op(simd::UnaryKind::Floor)
225    }
226
227    /// Element-wise ceil.
228    pub fn ceil(&self) -> Self {
229        self.unary_simd_op(simd::UnaryKind::Ceil)
230    }
231
232    /// Element-wise round.
233    pub fn round(&self) -> Self {
234        self.unary_simd_op(simd::UnaryKind::Round)
235    }
236
237    /// Element-wise sine (SIMD-accelerated polynomial approximation).
238    #[allow(unsafe_code)]
239    pub fn sin(&self) -> Self {
240        let len = self.len();
241        // SAFETY: all output elements are written before the tensor is returned.
242        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
243        simd::sin_dispatch(self.data(), &mut out);
244        Tensor::from_raw_parts(self.shape(), self.strides(), out)
245    }
246
247    /// Element-wise cosine (SIMD-accelerated polynomial approximation).
248    #[allow(unsafe_code)]
249    pub fn cos(&self) -> Self {
250        let len = self.len();
251        // SAFETY: all output elements are written before the tensor is returned.
252        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
253        simd::cos_dispatch(self.data(), &mut out);
254        Tensor::from_raw_parts(self.shape(), self.strides(), out)
255    }
256
257    /// Element-wise tangent (SIMD-accelerated via sin/cos).
258    #[allow(unsafe_code)]
259    pub fn tan(&self) -> Self {
260        let len = self.len();
261        // SAFETY: all output elements are written before the tensor is returned.
262        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
263        simd::tan_dispatch(self.data(), &mut out);
264        Tensor::from_raw_parts(self.shape(), self.strides(), out)
265    }
266
267    /// Element-wise arcsine.
268    pub fn asin(&self) -> Self {
269        self.unary_op(f32::asin)
270    }
271
272    /// Element-wise arccosine.
273    pub fn acos(&self) -> Self {
274        self.unary_op(f32::acos)
275    }
276
277    /// Element-wise arctangent.
278    pub fn atan(&self) -> Self {
279        self.unary_op(f32::atan)
280    }
281
282    /// Element-wise hyperbolic sine.
283    pub fn sinh(&self) -> Self {
284        self.unary_op(f32::sinh)
285    }
286
287    /// Element-wise hyperbolic cosine.
288    pub fn cosh(&self) -> Self {
289        self.unary_op(f32::cosh)
290    }
291
292    /// Element-wise base-2 logarithm.
293    pub fn log2(&self) -> Self {
294        self.unary_op(f32::log2)
295    }
296
297    /// Element-wise base-10 logarithm.
298    pub fn log10(&self) -> Self {
299        self.unary_op(f32::log10)
300    }
301
302    /// Convert radians to degrees.
303    pub fn degrees(&self) -> Self {
304        self.unary_op(|v| v.to_degrees())
305    }
306
307    /// Convert degrees to radians.
308    pub fn radians(&self) -> Self {
309        self.unary_op(|v| v.to_radians())
310    }
311
312    /// Clamp all elements to `[min, max]`.
313    #[allow(unsafe_code)]
314    pub fn clamp(&self, min: f32, max: f32) -> Self {
315        let len = self.len();
316        // SAFETY: all output elements are written before the tensor is returned.
317        let mut out = unsafe { AlignedVec::<f32>::uninitialized(len) };
318        simd::clamp_dispatch(self.data(), &mut out, min, max);
319        Tensor::from_raw_parts(self.shape(), self.strides(), out)
320    }
321
322    /// Scalar multiplication (broadcast multiply by a constant).
323    pub fn scale(&self, factor: f32) -> Self {
324        self.unary_op(|v| v * factor)
325    }
326
327    /// Add a scalar to all elements.
328    pub fn add_scalar(&self, value: f32) -> Self {
329        self.unary_op(|v| v + value)
330    }
331}