Skip to main content

ruxla_kernels/
complex.rs

1//! Complex numbers: the element types [`c64`] and [`c128`].
2//!
3//! The arithmetic follows XLA's CPU implementation (`ElementalIrEmitter`)
4//! where JAX lowers an operation to the StableHLO operation of the same
5//! name, and JAX's own formulas where JAX lowers it otherwise (`abs` with
6//! [`hypot`](Complex::abs), `sin`, and `cos`).
7
8/// A complex number with real and imaginary parts of type `F`.
9///
10/// It orders lexicographically (by the real part, then the imaginary part),
11/// as `lax.max`, `lax.min`, and `lax.sort` compare complex numbers.
12#[derive(Clone, Copy, Default, PartialEq, PartialOrd, Debug)]
13#[repr(C)]
14pub struct Complex<F> {
15    /// The real part.
16    pub re: F,
17    /// The imaginary part.
18    pub im: F,
19}
20
21/// A complex number made of two `f32`s (`complex64`).
22#[allow(non_camel_case_types)] // named like the other element types
23pub type c64 = Complex<f32>;
24
25/// A complex number made of two `f64`s (`complex128`).
26#[allow(non_camel_case_types)] // named like the other element types
27pub type c128 = Complex<f64>;
28
29impl<F> Complex<F> {
30    /// Creates a complex number from its real and imaginary parts.
31    pub const fn new(re: F, im: F) -> Self {
32        Self { re, im }
33    }
34}
35
36use std::ops::{Add, Div, Neg};
37
38macro_rules! impl_complex {
39    ($f:ident, $k:expr, $e_hi:expr) => {
40        impl std::ops::Add for Complex<$f> {
41            type Output = Self;
42            /// `x + y`.
43            #[inline]
44            fn add(self, o: Self) -> Self {
45                Self::new(self.re + o.re, self.im + o.im)
46            }
47        }
48
49        impl std::ops::Sub for Complex<$f> {
50            type Output = Self;
51            /// `x - y`.
52            #[inline]
53            fn sub(self, o: Self) -> Self {
54                Self::new(self.re - o.re, self.im - o.im)
55            }
56        }
57
58        impl std::ops::Mul for Complex<$f> {
59            type Output = Self;
60            /// `x * y`, with the multiplications and additions fused as XLA
61            /// does on CPU.
62            #[inline]
63            fn mul(self, o: Self) -> Self {
64                Self::new(
65                    self.re.mul_add(o.re, -(self.im * o.im)),
66                    self.im.mul_add(o.re, self.re * o.im),
67                )
68            }
69        }
70
71        impl std::ops::Neg for Complex<$f> {
72            type Output = Self;
73            /// `-x`.
74            #[inline]
75            fn neg(self) -> Self {
76                Self::new(-self.re, -self.im)
77            }
78        }
79
80        impl std::ops::Div for Complex<$f> {
81            type Output = Self;
82            /// `x / y` (see [`Complex::div_xla`]).
83            #[inline]
84            fn div(self, o: Self) -> Self {
85                self.div_xla(o)
86            }
87        }
88
89        impl Complex<$f> {
90            /// The complex conjugate.
91            #[inline]
92            pub fn conj(self) -> Self {
93                Self::new(self.re, -self.im)
94            }
95
96            /// `x / y` by Smith's algorithm, with XLA's handling of zero
97            /// and infinite operands when the quotient would be NaN.
98            pub fn div_xla(self, o: Self) -> Self {
99                let (a_r, a_i, b_r, b_i) = (self.re, self.im, o.re, o.im);
100                let (b_r_abs, b_i_abs) = (b_r.abs(), b_i.abs());
101                let (result_r, result_i) = if b_r_abs < b_i_abs {
102                    let ratio = b_r / b_i;
103                    let denom = b_i + ratio * b_r;
104                    ((ratio * a_r + a_i) / denom, (ratio * a_i - a_r) / denom)
105                } else {
106                    let ratio = b_i / b_r;
107                    let denom = b_r + ratio * b_i;
108                    ((ratio * a_i + a_r) / denom, (a_i - ratio * a_r) / denom)
109                };
110                if !(result_r.is_nan() && result_i.is_nan()) {
111                    return Self::new(result_r, result_i);
112                }
113                let inf = $f::INFINITY;
114                let (a_r_abs, a_i_abs) = (a_r.abs(), a_i.abs());
115                if b_r_abs == 0.0 && b_i_abs == 0.0 && (!a_r.is_nan() || !a_i.is_nan()) {
116                    // Case 1: a zero denominator.
117                    let s = inf.copysign(b_r);
118                    return Self::new(s * a_r, s * a_i);
119                }
120                let one_or_zero = |inf_: bool, sign: $f| {
121                    $f::copysign(if inf_ { 1.0 } else { 0.0 }, sign)
122                };
123                if (a_r_abs == inf || a_i_abs == inf) && b_r_abs != inf && b_i_abs != inf {
124                    // Case 2: an infinite numerator, a finite denominator.
125                    let x = one_or_zero(a_r_abs == inf, a_r);
126                    let y = one_or_zero(a_i_abs == inf, a_i);
127                    return Self::new(inf * (x * b_r + y * b_i), inf * (y * b_r - x * b_i));
128                }
129                if (b_r_abs == inf || b_i_abs == inf) && a_r_abs != inf && a_i_abs != inf {
130                    // Case 3: a finite numerator, an infinite denominator.
131                    let x = one_or_zero(b_r_abs == inf, b_r);
132                    let y = one_or_zero(b_i_abs == inf, b_i);
133                    return Self::new(0.0 * (a_r * x + a_i * y), 0.0 * (a_i * x - a_r * y));
134                }
135                Self::new(result_r, result_i)
136            }
137
138            /// `|x|`, computed as JAX lowers it (`lax.hypot` of the real and
139            /// imaginary parts, scaled by a power of two against overflow and
140            /// underflow).
141            pub fn abs(self) -> $f {
142                let (x1, x2) = (self.re, self.im);
143                let (a1, a2) = (x1.abs(), x2.abs());
144                let m = max_nan(a1, a2);
145                // `k` and `e_hi` as JAX computes them from `finfo`.
146                let k: i32 = $k;
147                let e_hi: i32 = $e_hi;
148                let hi = m >= (2.0 as $f).powi(e_hi);
149                let lo = m <= (2.0 as $f).powi(e_hi - k);
150                let (s_down, s_up) = ((2.0 as $f).powi(-k), (2.0 as $f).powi(k));
151                let scale = |x: $f| {
152                    if hi {
153                        x * s_down
154                    } else if lo {
155                        x * s_up
156                    } else {
157                        x
158                    }
159                };
160                let (y1, y2) = (scale(x1), scale(x2));
161                let inv_scale = if hi {
162                    s_up
163                } else if lo {
164                    s_down
165                } else {
166                    1.0
167                };
168                let r = (y1 * y1 + y2 * y2).sqrt() * inv_scale;
169                if a1 == $f::INFINITY || a2 == $f::INFINITY {
170                    $f::INFINITY
171                } else {
172                    r
173                }
174            }
175
176            /// `|x|` as XLA computes it (`max * sqrt(1 + (min / max)^2)`, with
177            /// the maximum and minimum of the parts' magnitudes taken as XLA's
178            /// fast min/max on CPU does), which `sign` uses.
179            fn xla_abs(self) -> $f {
180                let (min, max) = self.min_max_parts();
181                let div = min / max;
182                let r = max * (1.0 + div * div).sqrt();
183                if r.is_nan() { min } else { r }
184            }
185
186            /// The minimum and maximum of the magnitudes of the parts, picked
187            /// as XLA's fast min/max does (the first operand unless the second
188            /// compares less or greater).
189            #[inline]
190            fn min_max_parts(self) -> ($f, $f) {
191                let (x, y) = (self.re.abs(), self.im.abs());
192                let max = if y > x { y } else { x };
193                let min = if y < x { y } else { x };
194                (min, max)
195            }
196
197            /// `log|x|`, computed as `log(max) + log1p((min / max)^2) / 2`
198            /// without overflow.
199            fn log_abs(self) -> $f {
200                let (min, max) = self.min_max_parts();
201                if max == 0.0 {
202                    return $f::NEG_INFINITY;
203                }
204                if max == $f::INFINITY {
205                    return max;
206                }
207                if self.re.is_nan() || self.im.is_nan() {
208                    return $f::NAN;
209                }
210                let div = min / max;
211                max.ln() + 0.5 * (div * div).ln_1p()
212            }
213
214            /// The argument (`atan2(im, re)`).
215            #[inline]
216            pub fn arg(self) -> $f {
217                self.im.atan2(self.re)
218            }
219
220            /// `x / |x|`, or `x` where `x` is zero.
221            pub fn sign(self) -> Self {
222                if self.re.is_nan() || self.im.is_nan() {
223                    return Self::new($f::NAN, $f::NAN);
224                }
225                let abs = self.xla_abs();
226                if abs == 0.0 {
227                    self
228                } else {
229                    Self::new(self.re / abs, self.im / abs)
230                }
231            }
232
233            /// `e^x = e^a (cos b + i sin b)` (the imaginary part of a real
234            /// argument is kept, as in XLA).
235            pub fn exp(self) -> Self {
236                let (a, b) = (self.re, self.im);
237                let e = a.exp();
238                let im = if b == 0.0 { b } else { e * b.sin() };
239                Self::new(e * b.cos(), im)
240            }
241
242            /// `e^x - 1`.
243            pub fn expm1(self) -> Self {
244                // e^a cos b - 1 = expm1(a) cos b - 2 sin^2(b / 2).
245                let (a, b) = (self.re, self.im);
246                let h = (b * 0.5).sin();
247                let im = if b == 0.0 { b } else { a.exp() * b.sin() };
248                Self::new(a.exp_m1() * b.cos() - 2.0 * h * h, im)
249            }
250
251            /// `log|x| + i arg(x)`.
252            pub fn log(self) -> Self {
253                Self::new(self.log_abs(), self.arg())
254            }
255
256            /// `log(1 + x)`.
257            pub fn log1p(self) -> Self {
258                let (a, b) = (self.re, self.im);
259                // log|1 + x| = log1p(a^2 + b^2 + 2a) / 2 for small |x|.
260                let re = if a.abs() < 0.5 && b.abs() < 0.5 {
261                    0.5 * (a * a + b * b + 2.0 * a).ln_1p()
262                } else {
263                    Self::new(a + 1.0, b).log_abs()
264                };
265                Self::new(re, b.atan2(a + 1.0))
266            }
267
268            /// The principal square root.
269            pub fn sqrt(self) -> Self {
270                let (a, b) = (self.re, self.im);
271                if a == 0.0 && b == 0.0 {
272                    return Self::new(0.0, b);
273                }
274                if b.is_infinite() {
275                    return Self::new($f::INFINITY, b);
276                }
277                if a == $f::NEG_INFINITY {
278                    return if b.is_nan() {
279                        Self::new(b, $f::INFINITY)
280                    } else {
281                        Self::new(0.0, $f::INFINITY.copysign(b))
282                    };
283                }
284                if a == $f::INFINITY {
285                    return if b.is_nan() {
286                        Self::new(b, b)
287                    } else {
288                        Self::new(a, (0.0 as $f).copysign(b))
289                    };
290                }
291                // t = sqrt((|a| + |x|) / 2), scaled by 1/4 against overflow
292                // for large arguments.
293                let t = if a.abs().max(b.abs()) > $f::MAX / 8.0 {
294                    let r = Self::new(a * 0.25, b * 0.25).abs();
295                    (a.abs() * 0.25 + r).sqrt() * std::f64::consts::SQRT_2 as $f
296                } else {
297                    ((a.abs() + self.abs()) * 0.5).sqrt()
298                };
299                if a >= 0.0 {
300                    Self::new(t, b / (2.0 * t))
301                } else {
302                    Self::new(b.abs() / (2.0 * t), t.copysign(b))
303                }
304            }
305
306            /// `1 / sqrt(x)`.
307            pub fn rsqrt(self) -> Self {
308                if self.re.is_infinite() || self.im.is_infinite() {
309                    return Self::new(0.0, -0.0);
310                }
311                Self::new(1.0, 0.0).div(self.sqrt())
312            }
313
314            /// The sine, as JAX's `_sin_complex` computes it.
315            pub fn sin(self) -> Self {
316                let (a, b) = (self.re, self.im);
317                let (e1m, e2m) = (b.exp_m1(), (-b).exp_m1());
318                let snh = (e1m - e2m) / 2.0;
319                let csh = (e1m + e2m + 2.0) / 2.0;
320                let im = a.cos() * snh;
321                if a == 0.0 {
322                    Self::new(0.0, im)
323                } else {
324                    Self::new(a.sin() * csh, im)
325                }
326            }
327
328            /// The cosine, as JAX's `_cos_complex` computes it.
329            pub fn cos(self) -> Self {
330                let (a, b) = (self.re, self.im);
331                let (e1m, e2m) = (b.exp_m1(), (-b).exp_m1());
332                let snh = (e1m - e2m) / 2.0;
333                let csh = (e1m + e2m + 2.0) / 2.0;
334                let re = a.cos() * csh;
335                if a == 0.0 {
336                    Self::new(re, 0.0)
337                } else {
338                    Self::new(re, -a.sin() * snh)
339                }
340            }
341
342            /// The tangent: `tan(x) = -i tanh(i x)`.
343            pub fn tan(self) -> Self {
344                let t = Self::new(-self.im, self.re).tanh();
345                Self::new(t.im, -t.re)
346            }
347
348            /// The hyperbolic tangent.
349            pub fn tanh(self) -> Self {
350                let (a, b) = (self.re, self.im);
351                if b == 0.0 {
352                    return Self::new(a.tanh(), b);
353                }
354                // For large |a|, tanh(a) rounds to +-1 and the imaginary part
355                // underflows (to 0 also where it would be NaN, as in XLA).
356                if a.abs() > $f::MANTISSA_DIGITS as $f * 0.5 {
357                    let e = (-2.0 * a.abs()).exp();
358                    let im = 4.0 * b.sin() * b.cos() * e;
359                    let im = if im.is_nan() && !b.is_nan() { 0.0 } else { im };
360                    let im = if b.is_nan() { 0.0 } else { im };
361                    return Self::new((1.0 as $f).copysign(a), im);
362                }
363                // tanh(a + bi) = (tanh a (1 + tan^2 b) + i tan b (1 - tanh^2 a))
364                //              / (1 + tanh^2 a tan^2 b).
365                let (th, t) = (a.tanh(), b.tan());
366                let denom = 1.0 + th * th * t * t;
367                Self::new(th * (1.0 + t * t) / denom, t * (1.0 - th * th) / denom)
368            }
369
370            /// `1 / (1 + e^-x)`, as XLA expands `logistic`.
371            pub fn logistic(self) -> Self {
372                let one = Self::new(1.0, 0.0);
373                one.div(one.add(self.neg().exp()))
374            }
375
376            /// `x^y`: `e^(c log|x| - d arg x) (cos q + i sin q)` with `q = c
377            /// arg x + d log|x|` for `y = c + di`, with the special cases of
378            /// XLA's CPU implementation: `x^0` is 1, a positive real `x` to a
379            /// real `y` is real, `1^y` is 1, and `0^y` is 0 for real `y > 0`.
380            pub fn pow(self, y: Self) -> Self {
381                let (a, b, c, d) = (self.re, self.im, y.re, y.im);
382                if (c == 0.0 && d == 0.0) || (a == 1.0 && b == 0.0) {
383                    return Self::new(1.0, 0.0);
384                }
385                if d == 0.0 && b == 0.0 && a > 0.0 && !c.is_nan() {
386                    return Self::new(a.powf(c), 0.0);
387                }
388                if a == 0.0 && (b == 0.0 || b.is_nan()) && d == 0.0 && c > 0.0 {
389                    return Self::new(0.0, 0.0);
390                }
391                // log|x| of XLA's |x|, which overflows for the largest values.
392                let (lr, arg) = (self.xla_abs().ln(), b.atan2(a));
393                let coeff = (c * lr).exp() * (-d * arg).exp();
394                let q = c * arg + d * lr;
395                Self::new(coeff * q.cos(), coeff * q.sin())
396            }
397
398            /// The maximum, comparing lexicographically as JAX lowers `max`
399            /// of complex numbers (`y` unless `x` is greater).
400            #[inline]
401            pub fn max(self, o: Self) -> Self {
402                let gt = if self.re == o.re {
403                    self.im > o.im
404                } else {
405                    self.re > o.re
406                };
407                if gt { self } else { o }
408            }
409
410            /// The minimum, comparing lexicographically as JAX lowers `min`
411            /// of complex numbers (`y` unless `x` is less).
412            #[inline]
413            pub fn min(self, o: Self) -> Self {
414                let lt = if self.re == o.re {
415                    self.im < o.im
416                } else {
417                    self.re < o.re
418                };
419                if lt { self } else { o }
420            }
421
422            /// Whether both parts are finite.
423            #[inline]
424            pub fn is_finite(self) -> bool {
425                self.re.is_finite() && self.im.is_finite()
426            }
427        }
428    };
429}
430
431/// The maximum, propagating NaN (as XLA's `EmitFloatMax`).
432fn max_nan<F: num_like::Float>(a: F, b: F) -> F {
433    if a.is_nan_() || b.is_nan_() {
434        F::NAN_
435    } else if a > b {
436        a
437    } else {
438        b
439    }
440}
441
442mod num_like {
443    /// The floats that complex numbers are made of.
444    pub(super) trait Float: Copy + PartialOrd {
445        const NAN_: Self;
446        fn is_nan_(self) -> bool;
447    }
448    impl Float for f32 {
449        const NAN_: Self = f32::NAN;
450        fn is_nan_(self) -> bool {
451            self.is_nan()
452        }
453    }
454    impl Float for f64 {
455        const NAN_: Self = f64::NAN;
456        fn is_nan_(self) -> bool {
457            self.is_nan()
458        }
459    }
460}
461
462// k = (nmant - minexp + 1) / 2 and e_hi = (maxexp - 1) / 2 from `finfo`.
463impl_complex!(f32, 75, 63);
464impl_complex!(f64, 537, 511);
465
466#[cfg(test)]
467mod tests {
468    use super::*;
469    use std::ops::{Mul, Sub};
470
471    fn close(a: c128, b: c128) -> bool {
472        (a.re - b.re).abs() <= 1e-12 * (1.0 + b.re.abs())
473            && (a.im - b.im).abs() <= 1e-12 * (1.0 + b.im.abs())
474    }
475
476    #[test]
477    fn arithmetic() {
478        let x = c128::new(1.0, 2.0);
479        let y = c128::new(3.0, -1.0);
480        assert_eq!(x.mul(y), c128::new(5.0, 5.0));
481        assert!(close(x.div(y).mul(y), x));
482        assert_eq!(c128::new(3.0, 4.0).abs(), 5.0);
483        assert_eq!(c64::new(3e30, 4e30).abs(), 5e30);
484        assert_eq!(c64::new(3e-30, 4e-30).abs(), 5e-30);
485        assert_eq!(c128::new(f64::INFINITY, f64::NAN).abs(), f64::INFINITY);
486        // Division by zero gives infinities, as in XLA.
487        let q = c128::new(1.0, 1.0).div(c128::new(0.0, 0.0));
488        assert_eq!((q.re, q.im), (f64::INFINITY, f64::INFINITY));
489        let q = c128::new(1.0, 1.0).div(c128::new(f64::INFINITY, 0.0));
490        assert_eq!((q.re, q.im), (0.0, 0.0));
491    }
492
493    #[test]
494    fn functions() {
495        let x = c128::new(0.5, -1.25);
496        assert!(close(x.log().exp(), x));
497        assert!(close(x.sqrt().mul(x.sqrt()), x));
498        assert!(close(x.expm1(), x.exp().sub(c128::new(1.0, 0.0))));
499        assert!(close(x.log1p(), x.add(c128::new(1.0, 0.0)).log()));
500        let (s, c) = (x.sin(), x.cos());
501        assert!(close(s.mul(s).add(c.mul(c)), c128::new(1.0, 0.0)));
502        assert!(close(x.tan(), s.div(c)));
503        let i = c128::new(0.0, 1.0);
504        assert!(close(x.tanh(), x.mul(i).tan().div(i)));
505        assert!(close(x.pow(c128::new(2.0, 0.0)), x.mul(x)));
506        assert_eq!(
507            c128::new(0.0, 0.0).pow(c128::new(0.0, 0.0)),
508            c128::new(1.0, 0.0)
509        );
510        assert_eq!(c128::new(-4.0, 0.0).sqrt(), c128::new(0.0, 2.0));
511        assert_eq!(c128::new(-4.0, -0.0).sqrt(), c128::new(0.0, -2.0));
512        assert!(close(c128::new(3.0, 4.0).sign(), c128::new(0.6, 0.8)));
513    }
514
515    #[test]
516    fn order() {
517        let (a, b) = (c64::new(1.0, 5.0), c64::new(1.0, 7.0));
518        assert!(a < b);
519        assert_eq!(a.max(b), b);
520        assert_eq!(a.min(b), a);
521        assert_eq!(c64::new(2.0, 0.0).max(b), c64::new(2.0, 0.0));
522    }
523}