Skip to main content

ruxla_kernels/
special.rs

1//! Special functions: `lgamma`, `digamma`, `erf`, `erfc`, the exponentially
2//! scaled Bessel functions, the incomplete gamma and beta functions,
3//! `polygamma`, and `zeta`.
4//!
5//! Each function is written once, against [`Builder`], in the masked,
6//! vectorized style of XLA's and JAX's own implementations: loops carry a
7//! mask of the elements that have not converged, and the elements that
8//! have converged keep their state, so each element's result does not
9//! depend on the other elements. The kernels run the algorithms on scalars
10//! (`unary`, `binary`, `ternary`); `ruxla-prims` runs the same code
11//! on IR to lower the primitives that JAX lowers by tracing such code.
12//!
13//! The algorithms follow:
14//!
15//! - StableHLO's decomposition of CHLO (`ChloLegalizeToStablehlo.cpp`) for
16//!   `lgamma`, `digamma`, `erf`, `erfc`, `bessel_i1e`, `polygamma`, and
17//!   `zeta`, which XLA expands;
18//! - `jax._src.lax.special` for `igamma`, `igammac`, `igamma_grad_a`,
19//!   `random_gamma_grad`, `bessel_i0e`, and `regularized_incomplete_beta`.
20//!
21//! The operations are evaluated in the same order, so the results match XLA
22//! up to the implementations of `exp`, `log`, `sin`, and the like, and up
23//! to the fusion of multiplications and additions.
24
25mod coefficients;
26
27use coefficients::*;
28
29use crate::dtype::{Element, cast};
30use crate::ops::{BinaryOp, CompareOp, Ops, UnaryOp};
31
32/// The values a [`Builder::while_loop`] carries: masks and floats.
33pub struct Carry<B: Builder> {
34    /// The boolean values.
35    pub bools: Vec<B::B>,
36    /// The floating point values.
37    pub floats: Vec<B::F>,
38}
39
40impl<B: Builder> std::fmt::Debug for Carry<B> {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("Carry")
43            .field("bools", &self.bools.len())
44            .field("floats", &self.floats.len())
45            .finish()
46    }
47}
48
49impl<B: Builder> Clone for Carry<B> {
50    fn clone(&self) -> Self {
51        Self {
52            bools: self.bools.clone(),
53            floats: self.floats.clone(),
54        }
55    }
56}
57
58/// The operations the special functions are written with.
59///
60/// Floats ([`Builder::F`]) have one type, `f32` or `f64` (16-bit floats are
61/// computed in `f32`), and every value has the same shape.
62pub trait Builder: Sized {
63    /// A floating point value.
64    type F: Clone;
65    /// A boolean value.
66    type B: Clone;
67
68    /// Whether the floats are `f64` (otherwise `f32`).
69    fn is_f64(&self) -> bool;
70    /// A constant, rounded to the float type.
71    fn constant(&mut self, v: f64) -> Self::F;
72    /// A unary operation.
73    fn unary(&mut self, op: UnaryOp, x: &Self::F) -> Self::F;
74    /// A binary operation.
75    fn binary(&mut self, op: BinaryOp, x: &Self::F, y: &Self::F) -> Self::F;
76    /// A comparison.
77    fn compare(&mut self, op: CompareOp, x: &Self::F, y: &Self::F) -> Self::B;
78    /// A logical operation on masks (`And`, `Or`).
79    fn logical(&mut self, op: BinaryOp, x: &Self::B, y: &Self::B) -> Self::B;
80    /// Logical not.
81    fn not(&mut self, x: &Self::B) -> Self::B;
82    /// `pred ? on_true : on_false`, element by element.
83    fn select(&mut self, pred: &Self::B, on_true: &Self::F, on_false: &Self::F) -> Self::F;
84    /// A constant mask.
85    fn mask(&mut self, v: bool) -> Self::B;
86    /// Whether each element is finite.
87    fn is_finite(&mut self, x: &Self::F) -> Self::B;
88    /// Whether any element is true, broadcast to every element.
89    fn any(&mut self, x: &Self::B) -> Self::B;
90    /// Repeats `body` while `cond` holds (for any element).
91    fn while_loop(
92        &mut self,
93        init: Carry<Self>,
94        cond: &mut dyn FnMut(&mut Self, &Carry<Self>) -> Self::B,
95        body: &mut dyn FnMut(&mut Self, &Carry<Self>) -> Carry<Self>,
96    ) -> Carry<Self>;
97
98    /// `lgamma`, which a builder may emit as a primitive.
99    fn lgamma(&mut self, x: &Self::F) -> Self::F {
100        lgamma(self, x)
101    }
102    /// `digamma`, which a builder may emit as a primitive.
103    fn digamma(&mut self, x: &Self::F) -> Self::F {
104        digamma(self, x)
105    }
106}
107
108/// Shorthands for the operations of a [`Builder`].
109trait Ext: Builder {
110    fn c(&mut self, v: f64) -> Self::F {
111        self.constant(v)
112    }
113    fn add(&mut self, x: &Self::F, y: &Self::F) -> Self::F {
114        self.binary(BinaryOp::Add, x, y)
115    }
116    fn sub(&mut self, x: &Self::F, y: &Self::F) -> Self::F {
117        self.binary(BinaryOp::Sub, x, y)
118    }
119    fn mul(&mut self, x: &Self::F, y: &Self::F) -> Self::F {
120        self.binary(BinaryOp::Mul, x, y)
121    }
122    fn div(&mut self, x: &Self::F, y: &Self::F) -> Self::F {
123        self.binary(BinaryOp::Div, x, y)
124    }
125    fn addc(&mut self, x: &Self::F, v: f64) -> Self::F {
126        let c = self.c(v);
127        self.add(x, &c)
128    }
129    fn subc(&mut self, x: &Self::F, v: f64) -> Self::F {
130        let c = self.c(v);
131        self.sub(x, &c)
132    }
133    fn csub(&mut self, v: f64, x: &Self::F) -> Self::F {
134        let c = self.c(v);
135        self.sub(&c, x)
136    }
137    fn mulc(&mut self, x: &Self::F, v: f64) -> Self::F {
138        let c = self.c(v);
139        self.mul(x, &c)
140    }
141    fn cmul(&mut self, v: f64, x: &Self::F) -> Self::F {
142        let c = self.c(v);
143        self.mul(&c, x)
144    }
145    fn neg(&mut self, x: &Self::F) -> Self::F {
146        self.unary(UnaryOp::Neg, x)
147    }
148    fn abs(&mut self, x: &Self::F) -> Self::F {
149        self.unary(UnaryOp::Abs, x)
150    }
151    fn log(&mut self, x: &Self::F) -> Self::F {
152        self.unary(UnaryOp::Log, x)
153    }
154    fn log1p(&mut self, x: &Self::F) -> Self::F {
155        self.unary(UnaryOp::Log1p, x)
156    }
157    fn exp(&mut self, x: &Self::F) -> Self::F {
158        self.unary(UnaryOp::Exp, x)
159    }
160    fn sqrt(&mut self, x: &Self::F) -> Self::F {
161        self.unary(UnaryOp::Sqrt, x)
162    }
163    fn floor(&mut self, x: &Self::F) -> Self::F {
164        self.unary(UnaryOp::Floor, x)
165    }
166    fn cmp(&mut self, op: CompareOp, x: &Self::F, y: &Self::F) -> Self::B {
167        self.compare(op, x, y)
168    }
169    fn cmpc(&mut self, op: CompareOp, x: &Self::F, v: f64) -> Self::B {
170        let c = self.c(v);
171        self.compare(op, x, &c)
172    }
173    fn and(&mut self, x: &Self::B, y: &Self::B) -> Self::B {
174        self.logical(BinaryOp::And, x, y)
175    }
176    fn or(&mut self, x: &Self::B, y: &Self::B) -> Self::B {
177        self.logical(BinaryOp::Or, x, y)
178    }
179    fn or_all(&mut self, xs: &[Self::B]) -> Self::B {
180        let mut acc = xs[0].clone();
181        for x in &xs[1..] {
182            acc = self.or(&acc, x);
183        }
184        acc
185    }
186    fn selc(&mut self, pred: &Self::B, v: f64, on_false: &Self::F) -> Self::F {
187        let c = self.c(v);
188        self.select(pred, &c, on_false)
189    }
190    fn is_nan(&mut self, x: &Self::F) -> Self::B {
191        self.compare(CompareOp::Ne, x, x)
192    }
193    /// The machine epsilon of the float type.
194    fn eps(&self) -> f64 {
195        if self.is_f64() {
196            f64::EPSILON
197        } else {
198            f64::from(f32::EPSILON)
199        }
200    }
201    /// The largest finite value of the float type.
202    fn max_value(&self) -> f64 {
203        if self.is_f64() {
204            f64::MAX
205        } else {
206            f64::from(f32::MAX)
207        }
208    }
209    /// The smallest positive normal value of the float type.
210    fn tiny(&self) -> f64 {
211        if self.is_f64() {
212            f64::MIN_POSITIVE
213        } else {
214            f64::from(f32::MIN_POSITIVE)
215        }
216    }
217    /// The smallest positive subnormal value of the float type.
218    fn smallest(&self) -> f64 {
219        if self.is_f64() {
220            f64::from_bits(1)
221        } else {
222            f64::from(f32::from_bits(1))
223        }
224    }
225}
226
227impl<B: Builder> Ext for B {}
228
229use CompareOp::{Eq, Ge, Gt, Le, Lt, Ne};
230
231/// Evaluates `c[0] x^(n-1) + ... + c[n-1]` by Horner's rule.
232fn polynomial<B: Builder>(b: &mut B, x: &B::F, coefficients: &[f64]) -> B::F {
233    let mut poly = b.c(coefficients[0]);
234    for &c in &coefficients[1..] {
235        poly = b.mul(&poly, x);
236        poly = b.addc(&poly, c);
237    }
238    poly
239}
240
241/// Evaluates a Chebyshev series by Clenshaw's recurrence, as Cephes does.
242fn chebyshev<B: Builder>(b: &mut B, x: &B::F, coefficients: &[f64]) -> B::F {
243    let mut b0 = b.c(0.0);
244    let mut b1 = b0.clone();
245    let mut b2 = b0.clone();
246    for &c in coefficients {
247        b2 = b1;
248        b1 = b0;
249        let t = b.mul(x, &b1);
250        let t = b.sub(&t, &b2);
251        b0 = b.addc(&t, c);
252    }
253    let r = b.sub(&b0, &b2);
254    b.mulc(&r, 0.5)
255}
256
257/// Widens `f32` literals, so that coefficients written for `f32` round as
258/// they do in C++.
259fn widen<const N: usize>(c: [f32; N]) -> [f64; N] {
260    c.map(f64::from)
261}
262
263// ---------------------------------------------------------------------------
264// erf and erfc
265
266/// `erfc` for `|x| >= 1` (`f64`).
267fn erfc_ge_one_f64<B: Builder>(b: &mut B, x: &B::F) -> B::F {
268    let x_sq = b.mul(x, x);
269    let z = b.neg(&x_sq);
270    let exp_z = b.exp(&z);
271    let abs_x = b.abs(x);
272    let p = polynomial(b, &abs_x, &ERFC_P_F64);
273    let exp_p = b.mul(&exp_z, &p);
274    let q = polynomial(b, &abs_x, &ERFC_Q_F64);
275    let approx_1_8 = b.div(&exp_p, &q);
276    let r = polynomial(b, &abs_x, &ERFC_R_F64);
277    let exp_r = b.mul(&exp_z, &r);
278    let s = polynomial(b, &abs_x, &ERFC_S_F64);
279    let approx_8_inf = b.div(&exp_r, &s);
280    let lt8 = b.cmpc(Lt, &abs_x, 8.0);
281    let approx = b.select(&lt8, &approx_1_8, &approx_8_inf);
282    let underflow = b.cmpc(Lt, &z, -ERFC_MAXLOG_F64);
283    let clamped = b.selc(&underflow, 0.0, &approx);
284    let negative = b.cmpc(Lt, x, 0.0);
285    let reflected = b.csub(2.0, &clamped);
286    b.select(&negative, &reflected, &clamped)
287}
288
289/// `erf` for `|x| <= 1` (`f64`).
290fn erf_le_one_f64<B: Builder>(b: &mut B, x: &B::F) -> B::F {
291    let x_sq = b.mul(x, x);
292    let t = polynomial(b, &x_sq, &ERF_T_F64);
293    let xt = b.mul(x, &t);
294    let u = polynomial(b, &x_sq, &ERF_U_F64);
295    b.div(&xt, &u)
296}
297
298/// `erfc` for `|x| >= 1` (`f32`).
299fn erfc_ge_one_f32<B: Builder>(b: &mut B, x: &B::F) -> B::F {
300    let x_sq = b.mul(x, x);
301    let z = b.neg(&x_sq);
302    let abs_x = b.abs(x);
303    let one = b.c(1.0);
304    let rx_sq = b.div(&one, &x_sq);
305    let exp_z = b.exp(&z);
306    let r_abs = b.div(&one, &abs_x);
307    let e = b.mul(&exp_z, &r_abs);
308    let lt2 = b.cmpc(Lt, &abs_x, 2.0);
309    let p = polynomial(b, &rx_sq, &widen(ERFC_P_F32));
310    let r = polynomial(b, &rx_sq, &widen(ERFC_R_F32));
311    let poly = b.select(&lt2, &p, &r);
312    let approx = b.mul(&e, &poly);
313    let underflow = b.cmpc(Lt, &z, -ERFC_MAXLOG_F32);
314    let clamped = b.selc(&underflow, 0.0, &approx);
315    let negative = b.cmpc(Lt, x, 0.0);
316    let reflected = b.csub(2.0, &clamped);
317    b.select(&negative, &reflected, &clamped)
318}
319
320/// `erf` for `|x| <= 1` (`f32`).
321fn erf_le_one_f32<B: Builder>(b: &mut B, x: &B::F) -> B::F {
322    let x_sq = b.mul(x, x);
323    let t = polynomial(b, &x_sq, &widen(ERF_T_F32));
324    b.mul(x, &t)
325}
326
327/// The error function.
328pub fn erf<B: Builder>(b: &mut B, x: &B::F) -> B::F {
329    if b.is_f64() {
330        let erf_approx = erf_le_one_f64(b, x);
331        let erfc_approx = erfc_ge_one_f64(b, x);
332        let from_erfc = b.csub(1.0, &erfc_approx);
333        let abs_x = b.abs(x);
334        let lt1 = b.cmpc(Lt, &abs_x, 1.0);
335        return b.select(&lt1, &erf_approx, &from_erfc);
336    }
337    // The same rational approximation as Eigen's.
338    let lo = b.c(-4.0);
339    let hi = b.c(4.0);
340    let x = b.binary(BinaryOp::Max, x, &lo);
341    let x = b.binary(BinaryOp::Min, &x, &hi);
342    let x_sq = b.mul(&x, &x);
343    let a = polynomial(b, &x_sq, &widen(ERF_ALPHA_F32));
344    let bt = polynomial(b, &x_sq, &widen(ERF_BETA_F32));
345    let xa = b.mul(&x, &a);
346    let erf = b.div(&xa, &bt);
347    let lo = b.c(-1.0);
348    let hi = b.c(1.0);
349    let erf = b.binary(BinaryOp::Max, &erf, &lo);
350    b.binary(BinaryOp::Min, &erf, &hi)
351}
352
353/// The complementary error function.
354pub fn erfc<B: Builder>(b: &mut B, x: &B::F) -> B::F {
355    let (erfc_approx, erf_approx) = if b.is_f64() {
356        (erfc_ge_one_f64(b, x), erf_le_one_f64(b, x))
357    } else {
358        (erfc_ge_one_f32(b, x), erf_le_one_f32(b, x))
359    };
360    let from_erf = b.csub(1.0, &erf_approx);
361    let abs_x = b.abs(x);
362    let lt1 = b.cmpc(Lt, &abs_x, 1.0);
363    b.select(&lt1, &from_erf, &erfc_approx)
364}
365
366/// The inverse error function: M. Giles' approximation, as StableHLO
367/// decomposes `chlo.erf_inv`.
368pub fn erf_inv<B: Builder>(b: &mut B, x: &B::F) -> B::F {
369    let neg_x = b.neg(x);
370    let minus_x_sq = b.mul(x, &neg_x);
371    let l = b.log1p(&minus_x_sq);
372    let w = b.neg(&l);
373    let mut p;
374    if b.is_f64() {
375        let lt625 = b.cmpc(Lt, &w, 6.25);
376        let lt16 = b.cmpc(Lt, &w, 16.0);
377        let coefficient = |b: &mut B, i: usize| {
378            let mut c = b.c(ERF_INV_LT625_F64[i]);
379            if i < 19 {
380                let o = b.c(ERF_INV_LT16_F64[i]);
381                c = b.select(&lt625, &c, &o);
382            }
383            if i < 17 {
384                let o = b.c(ERF_INV_GE16_F64[i]);
385                c = b.select(&lt16, &c, &o);
386            }
387            c
388        };
389        let sqrt_w = b.sqrt(&w);
390        let w_minus = b.subc(&w, 3.125);
391        let c325 = b.c(3.25);
392        let c5 = b.c(5.0);
393        let s = b.select(&lt16, &c325, &c5);
394        let s = b.sub(&sqrt_w, &s);
395        let w = b.select(&lt625, &w_minus, &s);
396        p = coefficient(b, 0);
397        for i in 1..17 {
398            let c = coefficient(b, i);
399            let pw = b.mul(&p, &w);
400            p = b.add(&c, &pw);
401        }
402        for (i, mask) in (17..23).map(|i| (i, if i < 19 { &lt16 } else { &lt625 })) {
403            let c = coefficient(b, i);
404            let pw = b.mul(&p, &w);
405            let next = b.add(&c, &pw);
406            p = b.select(mask, &next, &p);
407        }
408    } else {
409        let lt = b.cmpc(Lt, &w, 5.0);
410        let coefficient = |b: &mut B, i: usize| {
411            let lo = b.c(f64::from(ERF_INV_LT5_F32[i]));
412            let hi = b.c(f64::from(ERF_INV_GE5_F32[i]));
413            b.select(&lt, &lo, &hi)
414        };
415        let w_lt = b.subc(&w, 2.5);
416        let sqrt_w = b.sqrt(&w);
417        let w_ge = b.subc(&sqrt_w, 3.0);
418        let w = b.select(&lt, &w_lt, &w_ge);
419        p = coefficient(b, 0);
420        for i in 1..ERF_INV_LT5_F32.len() {
421            let c = coefficient(b, i);
422            let pw = b.mul(&p, &w);
423            p = b.add(&c, &pw);
424        }
425    }
426    let result = b.mul(&p, x);
427    // erf_inv(+-1) = +-inf.
428    let abs_x = b.abs(x);
429    let is_one = b.cmpc(Eq, &abs_x, 1.0);
430    let inf = b.c(f64::INFINITY);
431    let x_inf = b.mul(x, &inf);
432    b.select(&is_one, &x_inf, &result)
433}
434
435// ---------------------------------------------------------------------------
436// lgamma and digamma (Lanczos' approximation)
437
438const LANCZOS_GAMMA: f64 = 7.0;
439
440/// `z = -x` if `x < 1/2`, otherwise `x - 1`; returns `(x < 1/2, z)`.
441fn lanczos_argument<B: Builder>(b: &mut B, x: &B::F) -> (B::B, B::F) {
442    let reflect = b.cmpc(Lt, x, 0.5);
443    let neg_x = b.neg(x);
444    let x_sub_one = b.subc(x, 1.0);
445    let z = b.select(&reflect, &neg_x, &x_sub_one);
446    (reflect, z)
447}
448
449/// `log(t)` for `t = z + 7.5`, as `log(7.5) + log1p(z / 7.5)`; returns
450/// `(t, log(t))`.
451fn lanczos_log_t<B: Builder>(b: &mut B, z: &B::F) -> (B::F, B::F) {
452    let lanczos_plus_half = b.c(LANCZOS_GAMMA + 0.5);
453    let t = b.add(&lanczos_plus_half, z);
454    let log_term = b.c((LANCZOS_GAMMA + 0.5).ln());
455    let q = b.div(z, &lanczos_plus_half);
456    let log1p_term = b.log1p(&q);
457    let log_t = b.add(&log_term, &log1p_term);
458    (t, log_t)
459}
460
461/// The logarithm of the absolute value of the gamma function.
462pub fn lgamma<B: Builder>(b: &mut B, x: &B::F) -> B::F {
463    let (reflect, z) = lanczos_argument(b, x);
464    let mut a = b.c(BASE_LANCZOS_COEFF);
465    for (i, &coeff) in LANCZOS_COEFFICIENTS.iter().enumerate() {
466        let c = b.c(coeff);
467        let zk = b.addc(&z, (i + 1) as f64);
468        let quotient = b.div(&c, &zk);
469        a = b.add(&a, &quotient);
470    }
471    let (t, log_t) = lanczos_log_t(b, &z);
472    // r = (z + 1/2 - t / log(t)) * log(t), which does not overflow.
473    let t_div_log_t = b.div(&t, &log_t);
474    let z_half = b.addc(&z, 0.5);
475    let sum = b.sub(&z_half, &t_div_log_t);
476    let r = b.mul(&sum, &log_t);
477    let log_a = b.log(&a);
478    let base = b.c((2f64.ln() + std::f64::consts::PI.ln()) / 2.0);
479    let lg = b.add(&base, &r);
480    let lg = b.add(&lg, &log_a);
481
482    // The reflection lgamma(x) = log(pi) - lgamma(1 - x) - log|sin(pi x)|,
483    // with sin(pi x) computed on the fractional part of |x|.
484    let abs = b.abs(x);
485    let floor = b.floor(&abs);
486    let abs_frac = b.sub(&abs, &floor);
487    let half = b.c(0.5);
488    let reduce = b.cmp(Lt, &half, &abs_frac);
489    let one_sub = b.csub(1.0, &abs_frac);
490    let abs_frac = b.select(&reduce, &one_sub, &abs_frac);
491    let pi_frac = b.cmul(std::f64::consts::PI, &abs_frac);
492    let sin = b.unary(UnaryOp::Sin, &pi_frac);
493    let denom = b.log(&sin);
494    let log_pi = b.c(std::f64::consts::PI.ln());
495    let reflection = b.sub(&log_pi, &denom);
496    let reflection = b.sub(&reflection, &lg);
497    let finite = b.is_finite(&denom);
498    let neg_denom = b.neg(&denom);
499    let reflection = b.select(&finite, &reflection, &neg_denom);
500    let lg = b.select(&reflect, &reflection, &lg);
501
502    // lgamma(+-inf) = inf.
503    let abs_x = b.abs(x);
504    let is_inf = b.cmpc(Eq, &abs_x, f64::INFINITY);
505    b.selc(&is_inf, f64::INFINITY, &lg)
506}
507
508/// The digamma function, the derivative of `lgamma`.
509pub fn digamma<B: Builder>(b: &mut B, x: &B::F) -> B::F {
510    let (reflect, z) = lanczos_argument(b, x);
511    let zero = b.c(0.0);
512    let mut a = b.c(BASE_LANCZOS_COEFF);
513    let mut a_prime = zero.clone();
514    for (i, &coeff) in LANCZOS_COEFFICIENTS.iter().enumerate() {
515        let c = b.c(coeff);
516        let zk = b.addc(&z, (i + 1) as f64);
517        let zk_sq = b.mul(&zk, &zk);
518        let q = b.div(&c, &zk_sq);
519        a_prime = b.sub(&a_prime, &q);
520        let q = b.div(&c, &zk);
521        a = b.add(&a, &q);
522    }
523    let (t, log_t) = lanczos_log_t(b, &z);
524    let a_prime_div_a = b.div(&a_prime, &a);
525    let gamma = b.c(LANCZOS_GAMMA);
526    let gamma_div_t = b.div(&gamma, &t);
527    let dg = b.add(&log_t, &a_prime_div_a);
528    let dg = b.sub(&dg, &gamma_div_t);
529
530    // The reflection digamma(x) = digamma(1 - x) - pi cot(pi x), with x
531    // shifted into [-0.5, 0.5].
532    let x_half = b.addc(x, 0.5);
533    let fl = b.floor(&x_half);
534    let fl = b.abs(&fl);
535    let reduced = b.add(x, &fl);
536    let pi = b.c(std::f64::consts::PI);
537    let pi_reduced = b.mul(&pi, &reduced);
538    let cos = b.unary(UnaryOp::Cos, &pi_reduced);
539    let sin = b.unary(UnaryOp::Sin, &pi_reduced);
540    let pi_cos = b.mul(&pi, &cos);
541    let cot = b.div(&pi_cos, &sin);
542    let reflection = b.sub(&dg, &cot);
543    let dg = b.select(&reflect, &reflection, &dg);
544
545    // Poles: NaN at negative integers, -inf at zero.
546    let is_zero = b.cmp(Eq, x, &zero);
547    let is_negative = b.cmp(Lt, x, &zero);
548    let floor_x = b.floor(x);
549    let is_int = b.cmp(Eq, x, &floor_x);
550    let negative_int = b.and(&is_negative, &is_int);
551    let dg = b.selc(&negative_int, f64::NAN, &dg);
552    b.selc(&is_zero, f64::NEG_INFINITY, &dg)
553}
554
555// ---------------------------------------------------------------------------
556// zeta and polygamma
557
558/// The Hurwitz zeta function `zeta(x, q)`.
559pub fn zeta<B: Builder>(b: &mut B, x: &B::F, q: &B::F) -> B::F {
560    const TERMS: usize = 12;
561    const ITERS: usize = 9;
562    const TWO_TERMS_MINUS_ONE: f64 = (2 * TERMS - 1) as f64;
563    let zero = b.c(0.0);
564    let one = b.c(1.0);
565    let mut acc = q.clone();
566    let neg_x = b.neg(x);
567    let mut power_sum = b.binary(BinaryOp::Pow, q, &neg_x);
568    for _ in 0..ITERS {
569        acc = b.add(&acc, &one);
570        let q_neg_power = b.binary(BinaryOp::Pow, &acc, &neg_x);
571        power_sum = b.add(&power_sum, &q_neg_power);
572    }
573    acc = b.add(&acc, &one);
574    let q_neg_power = b.binary(BinaryOp::Pow, &acc, &neg_x);
575    let x_minus_one = b.sub(x, &one);
576    let neg_x_minus_one = b.neg(&x_minus_one);
577    let acc_pow = b.binary(BinaryOp::Pow, &acc, &neg_x_minus_one);
578    let correction = b.div(&acc_pow, &x_minus_one);
579    let acc_sq = b.mul(&acc, &acc);
580    let rsqrt_acc = b.div(&one, &acc_sq);
581    let mut horner_sum = zero.clone();
582    for (i, &coeff) in ZETA_COEFFS.iter().enumerate().take(TERMS - 1) {
583        let lhs = b.addc(x, TWO_TERMS_MINUS_ONE - 1.0 - 2.0 * i as f64);
584        let rhs = b.addc(x, TWO_TERMS_MINUS_ONE - 2.0 - 2.0 * i as f64);
585        let product = b.mul(&lhs, &rhs);
586        let s = b.addc(&horner_sum, 1.0 / coeff);
587        let s = b.mul(&rsqrt_acc, &s);
588        horner_sum = b.mul(&product, &s);
589    }
590    let x_div_acc = b.div(x, &acc);
591    let tail = b.addc(&horner_sum, 1.0 / ZETA_COEFFS[TERMS - 1]);
592    let tail = b.mul(&x_div_acc, &tail);
593    let half = b.c(0.5);
594    let tail = b.add(&half, &tail);
595    let tail = b.mul(&q_neg_power, &tail);
596    let accurate = b.add(&power_sum, &correction);
597    let accurate = b.add(&accurate, &tail);
598
599    // The partial sum alone, if it is accurate enough.
600    let abs_q_neg_power = b.abs(&q_neg_power);
601    let abs_power_sum = b.abs(&power_sum);
602    let smallest = b.smallest();
603    let bound = b.mulc(&abs_power_sum, smallest);
604    let small = b.cmp(Lt, &abs_q_neg_power, &bound);
605    let mut out = b.select(&small, &power_sum, &accurate);
606
607    // Not defined for x < 1.
608    let x_lt_one = b.cmp(Lt, x, &one);
609    out = b.selc(&x_lt_one, f64::NAN, &out);
610    // For q <= 0, x must be an integer.
611    let q_le_zero = b.cmp(Le, q, &zero);
612    let floor_x = b.floor(x);
613    let x_not_int = b.cmp(Ne, x, &floor_x);
614    let domain_error = b.and(&q_le_zero, &x_not_int);
615    out = b.selc(&domain_error, f64::NAN, &out);
616    // Poles at integers q <= 0, +inf only for even integers x.
617    let floor_q = b.floor(q);
618    let q_is_int = b.cmp(Eq, q, &floor_q);
619    let at_pole = b.and(&q_le_zero, &q_is_int);
620    let x_is_int = b.cmp(Eq, x, &floor_x);
621    let two = b.c(2.0);
622    let x_rem = b.binary(BinaryOp::Rem, x, &two);
623    let x_is_even = b.cmp(Eq, &x_rem, &zero);
624    let x_is_even_int = b.and(&x_is_int, &x_is_even);
625    let inf = b.c(f64::INFINITY);
626    let nan = b.c(f64::NAN);
627    let pole = b.select(&x_is_even_int, &inf, &nan);
628    out = b.select(&at_pole, &pole, &out);
629    // x = 1 is the harmonic series.
630    let x_is_one = b.cmp(Eq, x, &one);
631    b.select(&x_is_one, &inf, &out)
632}
633
634/// The polygamma function `psi^(n)(x)`.
635pub fn polygamma<B: Builder>(b: &mut B, n: &B::F, x: &B::F) -> B::F {
636    let one = b.c(1.0);
637    let two = b.c(2.0);
638    let n_rem = b.binary(BinaryOp::Rem, n, &two);
639    let sign = b.mul(&two, &n_rem);
640    let sign = b.sub(&sign, &one);
641    let n_plus_one = b.add(n, &one);
642    let lg = b.lgamma(&n_plus_one);
643    let factorial = b.exp(&lg);
644    let z = zeta(b, &n_plus_one, x);
645    let result = b.mul(&sign, &factorial);
646    let result = b.mul(&result, &z);
647    let zero = b.c(0.0);
648    let n_is_zero = b.cmp(Eq, n, &zero);
649    let dg = b.digamma(x);
650    let result = b.select(&n_is_zero, &dg, &result);
651    let floor_n = b.floor(n);
652    let non_int = b.cmp(Ne, n, &floor_n);
653    let negative = b.cmp(Lt, n, &zero);
654    let non_natural = b.or(&non_int, &negative);
655    b.selc(&non_natural, f64::NAN, &result)
656}
657
658// ---------------------------------------------------------------------------
659// Bessel functions
660
661/// `exp(-|x|) I0(x)`, as `jax._src.lax.special.bessel_i0e_impl`.
662pub fn bessel_i0e<B: Builder>(b: &mut B, x: &B::F) -> B::F {
663    let (a, bc): (&[f64], &[f64]) = if b.is_f64() {
664        (&I0E_A_F64, &I0E_B_F64)
665    } else {
666        (&I0E_A_F32, &I0E_B_F32)
667    };
668    let x = b.abs(x);
669    let half = b.c(0.5);
670    let hx = b.mul(&half, &x);
671    let arg = b.subc(&hx, 2.0);
672    let le8 = chebyshev(b, &arg, a);
673    let thirty_two = b.c(32.0);
674    let q = b.div(&thirty_two, &x);
675    let arg = b.subc(&q, 2.0);
676    let gt8 = chebyshev(b, &arg, bc);
677    let sqrt = b.sqrt(&x);
678    let gt8 = b.div(&gt8, &sqrt);
679    let is_le8 = b.cmpc(Le, &x, 8.0);
680    b.select(&is_le8, &le8, &gt8)
681}
682
683/// `exp(-|x|) I1(x)`, as StableHLO decomposes `chlo.bessel_i1e`.
684pub fn bessel_i1e<B: Builder>(b: &mut B, x: &B::F) -> B::F {
685    let (a, bc): (Vec<f64>, Vec<f64>) = if b.is_f64() {
686        (I1E_A_F64.to_vec(), I1E_B_F64.to_vec())
687    } else {
688        (widen(I1E_A_F32).to_vec(), widen(I1E_B_F32).to_vec())
689    };
690    let z = b.abs(x);
691    let half = b.c(0.5);
692    let tmp = b.mul(&half, &z);
693    let tmp = b.subc(&tmp, 2.0);
694    let le8 = chebyshev(b, &tmp, &a);
695    let le8 = b.mul(&z, &le8);
696    let thirty_two = b.c(32.0);
697    let tmp = b.div(&thirty_two, &z);
698    let tmp = b.subc(&tmp, 2.0);
699    let gt8 = chebyshev(b, &tmp, &bc);
700    let sqrt = b.sqrt(&z);
701    let gt8 = b.div(&gt8, &sqrt);
702    let is_le8 = b.cmpc(Le, &z, 8.0);
703    let sel = b.select(&is_le8, &le8, &gt8);
704    let sign = b.unary(UnaryOp::Sign, x);
705    b.mul(&sign, &sel)
706}
707
708// ---------------------------------------------------------------------------
709// The incomplete gamma function
710
711#[derive(Clone, Copy, PartialEq)]
712enum IgammaMode {
713    Value,
714    Derivative,
715    SampleDerivative,
716}
717
718/// The power series of `igamma`.
719fn igamma_series<B: Builder>(
720    b: &mut B,
721    ax: &B::F,
722    x: &B::F,
723    a: &B::F,
724    enabled: &B::B,
725    mode: IgammaMode,
726) -> B::F {
727    let eps = b.eps();
728    let one = b.c(1.0);
729    let zero = b.c(0.0);
730    // Floats: r, c, ans, dc_da, dans_da.
731    let init = Carry {
732        bools: vec![enabled.clone()],
733        floats: vec![a.clone(), one.clone(), one, zero.clone(), zero],
734    };
735    let out = b.while_loop(init, &mut |b, s| b.any(&s.bools[0]), &mut |b, s| {
736        let enabled = &s.bools[0];
737        let [r0, c0, ans0, dc_da0, dans_da0] = &s.floats[..] else {
738            unreachable!()
739        };
740        let r = b.addc(r0, 1.0);
741        let x_r = b.div(x, &r);
742        let t1 = b.mul(dc_da0, &x_r);
743        let cx = b.mul(c0, x);
744        let rr = b.mul(&r, &r);
745        let t2 = b.div(&cx, &rr);
746        let dc_da = b.sub(&t1, &t2);
747        let dans_da = b.add(dans_da0, &dc_da);
748        let c = b.mul(c0, &x_r);
749        let ans = b.add(ans0, &c);
750        let conditional = if mode == IgammaMode::Value {
751            let ratio = b.div(&c, &ans);
752            let gt = b.cmpc(Gt, &ratio, eps);
753            b.and(enabled, &gt)
754        } else {
755            let ratio = b.div(&dc_da, &dans_da);
756            let ratio = b.abs(&ratio);
757            let gt = b.cmpc(Gt, &ratio, eps);
758            b.and(enabled, &gt)
759        };
760        let floats = [r, c, ans, dc_da, dans_da]
761            .iter()
762            .zip(&s.floats)
763            .map(|(new, old)| b.select(enabled, new, old))
764            .collect();
765        Carry {
766            bools: vec![conditional],
767            floats,
768        }
769    });
770    let ans = &out.floats[2];
771    let dans_da = &out.floats[4];
772    if mode == IgammaMode::Value {
773        let p = b.mul(ans, ax);
774        return b.div(&p, a);
775    }
776    let log_x = b.log(x);
777    let a1 = b.addc(a, 1.0);
778    let dg = b.digamma(&a1);
779    let dlogax_da = b.sub(&log_x, &dg);
780    let t = b.mul(ans, &dlogax_da);
781    if mode == IgammaMode::Derivative {
782        let s = b.add(&t, dans_da);
783        let p = b.mul(ax, &s);
784        b.div(&p, a)
785    } else {
786        let s = b.add(dans_da, &t);
787        let s = b.neg(&s);
788        let p = b.mul(&s, x);
789        b.div(&p, a)
790    }
791}
792
793/// The continued fraction of `igammac`.
794fn igammac_continued_fraction<B: Builder>(
795    b: &mut B,
796    ax: &B::F,
797    x: &B::F,
798    a: &B::F,
799    enabled: &B::B,
800    mode: IgammaMode,
801) -> B::F {
802    let eps = b.eps();
803    let y = b.csub(1.0, a);
804    let xy = b.add(x, &y);
805    let z = b.addc(&xy, 1.0);
806    let c = b.c(0.0);
807    let pkm2 = b.c(1.0);
808    let qkm2 = x.clone();
809    let pkm1 = b.addc(x, 1.0);
810    let qkm1 = b.mul(&z, x);
811    let ans = b.div(&pkm1, &qkm1);
812    let t = b.c(1.0);
813    let dpkm2_da = b.c(0.0);
814    let dqkm2_da = b.c(0.0);
815    let dpkm1_da = b.c(0.0);
816    let dqkm1_da = b.neg(x);
817    let p = b.mul(&ans, &dqkm1_da);
818    let p = b.sub(&dpkm1_da, &p);
819    let dans_da = b.div(&p, &qkm1);
820    // Floats: ans, t, y, z, c, pkm1, qkm1, pkm2, qkm2, dpkm2_da, dqkm2_da,
821    // dpkm1_da, dqkm1_da, dans_da.
822    let init = Carry {
823        bools: vec![enabled.clone()],
824        floats: vec![
825            ans, t, y, z, c, pkm1, qkm1, pkm2, qkm2, dpkm2_da, dqkm2_da, dpkm1_da, dqkm1_da,
826            dans_da,
827        ],
828    };
829    let out = b.while_loop(
830        init,
831        &mut |b, s| {
832            let c_lt = b.cmpc(Lt, &s.floats[4], 2000.0);
833            let c_lt = b.any(&c_lt);
834            let any = b.any(&s.bools[0]);
835            b.and(&c_lt, &any)
836        },
837        &mut |b, s| {
838            let enabled = &s.bools[0];
839            let [
840                ans0,
841                _t0,
842                y0,
843                z0,
844                c0,
845                pkm1,
846                qkm1,
847                pkm2,
848                qkm2,
849                dpkm2_da,
850                dqkm2_da,
851                dpkm1_da,
852                dqkm1_da,
853                dans_da0,
854            ] = &s.floats[..]
855            else {
856                unreachable!()
857            };
858            let c = b.addc(c0, 1.0);
859            let y = b.addc(y0, 1.0);
860            let z = b.addc(z0, 2.0);
861            let yc = b.mul(&y, &c);
862            let t1 = b.mul(pkm1, &z);
863            let t2 = b.mul(pkm2, &yc);
864            let pk = b.sub(&t1, &t2);
865            let t1 = b.mul(qkm1, &z);
866            let t2 = b.mul(qkm2, &yc);
867            let qk = b.sub(&t1, &t2);
868            let qk_nonzero = b.cmpc(Ne, &qk, 0.0);
869            let r = b.div(&pk, &qk);
870            let d = b.sub(ans0, &r);
871            let d = b.div(&d, &r);
872            let d = b.abs(&d);
873            let t = b.selc_rev(&qk_nonzero, &d, 1.0);
874            let ans = b.select(&qk_nonzero, &r, ans0);
875
876            let t1 = b.mul(dpkm1_da, &z);
877            let t1 = b.sub(&t1, pkm1);
878            let t2 = b.mul(dpkm2_da, &yc);
879            let t1 = b.sub(&t1, &t2);
880            let t2 = b.mul(pkm2, &c);
881            let dpk_da = b.add(&t1, &t2);
882            let t1 = b.mul(dqkm1_da, &z);
883            let t1 = b.sub(&t1, qkm1);
884            let t2 = b.mul(dqkm2_da, &yc);
885            let t1 = b.sub(&t1, &t2);
886            let t2 = b.mul(qkm2, &c);
887            let dqk_da = b.add(&t1, &t2);
888            let p = b.mul(&ans, &dqk_da);
889            let p = b.sub(&dpk_da, &p);
890            let p = b.div(&p, &qk);
891            let dans_da = b.select(&qk_nonzero, &p, dans_da0);
892            let g = b.sub(&dans_da, dans_da0);
893            let g = b.abs(&g);
894            let grad_conditional = b.selc_rev(&qk_nonzero, &g, 1.0);
895
896            let (mut pkm2n, mut pkm1n, mut qkm2n, mut qkm1n) =
897                (pkm1.clone(), pk.clone(), qkm1.clone(), qk);
898            let (mut dpkm2n, mut dqkm2n, mut dpkm1n, mut dqkm1n) =
899                (dpkm1_da.clone(), dqkm1_da.clone(), dpk_da, dqk_da);
900            let abs_pk = b.abs(&pk);
901            let big = b.c(1.0 / eps);
902            let rescale = b.cmp(Gt, &abs_pk, &big);
903            for v in [
904                &mut pkm2n,
905                &mut pkm1n,
906                &mut qkm2n,
907                &mut qkm1n,
908                &mut dpkm2n,
909                &mut dqkm2n,
910                &mut dpkm1n,
911                &mut dqkm1n,
912            ] {
913                let scaled = b.mulc(v, eps);
914                *v = b.select(&rescale, &scaled, v);
915            }
916            let conditional = if mode == IgammaMode::Value {
917                let gt = b.cmpc(Gt, &t, eps);
918                b.and(enabled, &gt)
919            } else {
920                let gt = b.cmpc(Gt, &grad_conditional, eps);
921                b.and(enabled, &gt)
922            };
923            let new = [
924                ans, t, y, z, c, pkm1n, qkm1n, pkm2n, qkm2n, dpkm2n, dqkm2n, dpkm1n, dqkm1n,
925                dans_da,
926            ];
927            let floats = new
928                .iter()
929                .zip(&s.floats)
930                .enumerate()
931                .map(|(i, (new, old))| {
932                    // The counter `c` advances for every element.
933                    if i == 4 {
934                        new.clone()
935                    } else {
936                        b.select(enabled, new, old)
937                    }
938                })
939                .collect();
940            Carry {
941                bools: vec![conditional],
942                floats,
943            }
944        },
945    );
946    let ans = &out.floats[0];
947    if mode == IgammaMode::Value {
948        return b.mul(ans, ax);
949    }
950    let dans_da = &out.floats[13];
951    let log_x = b.log(x);
952    let dg = b.digamma(a);
953    let dlogax_da = b.sub(&log_x, &dg);
954    let t = b.mul(ans, &dlogax_da);
955    if mode == IgammaMode::Derivative {
956        let s = b.add(&t, dans_da);
957        b.mul(ax, &s)
958    } else {
959        let s = b.add(dans_da, &t);
960        let s = b.neg(&s);
961        b.mul(&s, x)
962    }
963}
964
965/// `pred ? on_true : v`.
966trait SelcRev: Builder {
967    fn selc_rev(&mut self, pred: &Self::B, on_true: &Self::F, v: f64) -> Self::F {
968        let c = self.c(v);
969        self.select(pred, on_true, &c)
970    }
971}
972
973impl<B: Builder> SelcRev for B {}
974
975/// `a log(x) - x - lgamma(a)`, and whether it underflows `exp`.
976fn log_ax<B: Builder>(b: &mut B, a: &B::F, x: &B::F) -> (B::F, B::B) {
977    let log_x = b.log(x);
978    let t = b.mul(a, &log_x);
979    let t = b.sub(&t, x);
980    let lg = b.lgamma(a);
981    let ax = b.sub(&t, &lg);
982    let max = b.max_value();
983    let max = b.c(max);
984    let log_max = b.log(&max);
985    let neg_log_max = b.neg(&log_max);
986    let underflow = b.cmp(Lt, &ax, &neg_log_max);
987    (ax, underflow)
988}
989
990/// The regularized lower incomplete gamma function `P(a, x)`.
991pub fn igamma<B: Builder>(b: &mut B, a: &B::F, x: &B::F) -> B::F {
992    let a_nan = b.is_nan(a);
993    let x_nan = b.is_nan(x);
994    let is_nan = b.or(&a_nan, &x_nan);
995    let x_is_infinity = b.cmpc(Eq, x, f64::INFINITY);
996    let a_is_infinity = b.cmpc(Eq, a, f64::INFINITY);
997    let a_is_zero = b.cmpc(Eq, a, 0.0);
998    let x_is_zero = b.cmpc(Eq, x, 0.0);
999    let x_neg = b.cmpc(Lt, x, 0.0);
1000    let a_neg = b.cmpc(Lt, a, 0.0);
1001    let both_zero = b.and(&a_is_zero, &x_is_zero);
1002    let both_inf = b.and(&a_is_infinity, &x_is_infinity);
1003    let domain_error = b.or_all(&[x_neg, a_neg, both_zero, both_inf, is_nan]);
1004    let x_ge1 = b.cmpc(Ge, x, 1.0);
1005    let x_gt_a = b.cmp(Gt, x, a);
1006    let use_igammac = b.and(&x_ge1, &x_gt_a);
1007    let (ax, underflow) = log_ax(b, a, x);
1008    let ax = b.exp(&ax);
1009    let disabled = b.or_all(&[
1010        x_is_zero.clone(),
1011        domain_error.clone(),
1012        underflow,
1013        x_is_infinity.clone(),
1014        a_is_infinity.clone(),
1015    ]);
1016    let enabled = b.not(&disabled);
1017    let cf_enabled = b.and(&enabled, &use_igammac);
1018    let cf = igammac_continued_fraction(b, &ax, x, a, &cf_enabled, IgammaMode::Value);
1019    let cf = b.csub(1.0, &cf);
1020    let not_igammac = b.not(&use_igammac);
1021    let series_enabled = b.and(&enabled, &not_igammac);
1022    let series = igamma_series(b, &ax, x, a, &series_enabled, IgammaMode::Value);
1023    let out = b.select(&use_igammac, &cf, &series);
1024    let out = b.selc(&a_is_infinity, 0.0, &out);
1025    let out = b.selc(&x_is_zero, 0.0, &out);
1026    let out = b.selc(&x_is_infinity, 1.0, &out);
1027    b.selc(&domain_error, f64::NAN, &out)
1028}
1029
1030/// The regularized upper incomplete gamma function `Q(a, x)`.
1031pub fn igammac<B: Builder>(b: &mut B, a: &B::F, x: &B::F) -> B::F {
1032    let a_nan = b.is_nan(a);
1033    let x_nan = b.is_nan(x);
1034    let is_nan = b.or(&a_nan, &x_nan);
1035    let a_is_zero = b.cmpc(Eq, a, 0.0);
1036    let x_is_zero = b.cmpc(Eq, x, 0.0);
1037    let x_is_infinity = b.cmpc(Eq, x, f64::INFINITY);
1038    let a_is_infinity = b.cmpc(Eq, a, f64::INFINITY);
1039    let x_neg = b.cmpc(Lt, x, 0.0);
1040    let a_neg = b.cmpc(Lt, a, 0.0);
1041    let both_zero = b.and(&a_is_zero, &x_is_zero);
1042    let both_inf = b.and(&a_is_infinity, &x_is_infinity);
1043    let domain_error = b.or_all(&[x_neg, a_neg, both_zero, both_inf, is_nan]);
1044    let x_lt1 = b.cmpc(Lt, x, 1.0);
1045    let x_lt_a = b.cmp(Lt, x, a);
1046    let use_igamma = b.or(&x_lt1, &x_lt_a);
1047    let (ax, underflow) = log_ax(b, a, x);
1048    let disabled = b.or_all(&[
1049        domain_error.clone(),
1050        underflow,
1051        x_is_infinity.clone(),
1052        a_is_zero.clone(),
1053        a_is_infinity.clone(),
1054    ]);
1055    let enabled = b.not(&disabled);
1056    let ax = b.exp(&ax);
1057    let series_enabled = b.and(&enabled, &use_igamma);
1058    let series = igamma_series(b, &ax, x, a, &series_enabled, IgammaMode::Value);
1059    let not_igamma = b.not(&use_igamma);
1060    let cf_enabled = b.and(&enabled, &not_igamma);
1061    let cf = igammac_continued_fraction(b, &ax, x, a, &cf_enabled, IgammaMode::Value);
1062    let from_series = b.csub(1.0, &series);
1063    let out = b.select(&use_igamma, &from_series, &cf);
1064    let out = b.selc(&a_is_infinity, 1.0, &out);
1065    let zero_out = b.or(&x_is_infinity, &a_is_zero);
1066    let out = b.selc(&zero_out, 0.0, &out);
1067    b.selc(&domain_error, f64::NAN, &out)
1068}
1069
1070/// The derivative of `igamma` with respect to `a`, or of a sample of
1071/// `Gamma(a, 1)` with respect to `a` (`random_gamma_grad`).
1072fn igamma_derivative<B: Builder>(b: &mut B, a: &B::F, x: &B::F, mode: IgammaMode) -> B::F {
1073    let a_nan = b.is_nan(a);
1074    let x_nan = b.is_nan(x);
1075    let is_nan = b.or(&a_nan, &x_nan);
1076    let x_is_zero = b.cmpc(Eq, x, 0.0);
1077    let x_neg = b.cmpc(Lt, x, 0.0);
1078    let a_nonpositive = b.cmpc(Le, a, 0.0);
1079    let domain_error = b.or(&x_neg, &a_nonpositive);
1080    let x_gt1 = b.cmpc(Gt, x, 1.0);
1081    let x_gt_a = b.cmp(Gt, x, a);
1082    let use_igammac = b.and(&x_gt1, &x_gt_a);
1083    let (ax, underflow) = log_ax(b, a, x);
1084    let ax = b.exp(&ax);
1085    let disabled = b.or_all(&[
1086        x_is_zero.clone(),
1087        domain_error.clone(),
1088        underflow,
1089        is_nan.clone(),
1090    ]);
1091    let enabled = b.not(&disabled);
1092    let cf_enabled = b.and(&enabled, &use_igammac);
1093    let cf = igammac_continued_fraction(b, &ax, x, a, &cf_enabled, mode);
1094    let cf = b.neg(&cf);
1095    let not_igammac = b.not(&use_igammac);
1096    let series_enabled = b.and(&enabled, &not_igammac);
1097    let series = igamma_series(b, &ax, x, a, &series_enabled, mode);
1098    let out = b.select(&use_igammac, &cf, &series);
1099    let out = b.selc(&x_is_zero, 0.0, &out);
1100    let invalid = b.or(&domain_error, &is_nan);
1101    b.selc(&invalid, f64::NAN, &out)
1102}
1103
1104/// The derivative of `igamma(a, x)` with respect to `a`.
1105pub fn igamma_grad_a<B: Builder>(b: &mut B, a: &B::F, x: &B::F) -> B::F {
1106    igamma_derivative(b, a, x, IgammaMode::Derivative)
1107}
1108
1109/// The derivative of a sample `x` of `Gamma(a, 1)` with respect to `a`.
1110pub fn random_gamma_grad<B: Builder>(b: &mut B, a: &B::F, x: &B::F) -> B::F {
1111    igamma_derivative(b, a, x, IgammaMode::SampleDerivative)
1112}
1113
1114// ---------------------------------------------------------------------------
1115// The incomplete beta function
1116
1117/// The regularized incomplete beta function `I_x(a, b)`, by the continued
1118/// fraction of DLMF 8.17.22 evaluated with the modified Lentz algorithm.
1119pub fn regularized_incomplete_beta<B: Builder>(bd: &mut B, a: &B::F, b: &B::F, x: &B::F) -> B::F {
1120    let eps = bd.eps();
1121    let a_eq0 = bd.cmpc(Eq, a, 0.0);
1122    let b_inf = bd.cmpc(Eq, b, f64::INFINITY);
1123    let a_is_zero = bd.or(&a_eq0, &b_inf);
1124    let b_eq0 = bd.cmpc(Eq, b, 0.0);
1125    let a_inf = bd.cmpc(Eq, a, f64::INFINITY);
1126    let b_is_zero = bd.or(&b_eq0, &a_inf);
1127    let x_is_zero = bd.cmpc(Eq, x, 0.0);
1128    let x_is_one = bd.cmpc(Eq, x, 1.0);
1129    let x_not_zero = bd.not(&x_is_zero);
1130    let x_not_one = bd.not(&x_is_one);
1131    let a_nan = bd.is_nan(a);
1132    let b_nan = bd.is_nan(b);
1133    let x_nan = bd.is_nan(x);
1134    let is_nan = bd.or(&a_nan, &b_nan);
1135    let is_nan = bd.or(&is_nan, &x_nan);
1136    let t1 = bd.and(&b_is_zero, &x_not_one);
1137    let t2 = bd.and(&a_is_zero, &x_is_zero);
1138    let result_is_zero = bd.or(&t1, &t2);
1139    let t1 = bd.and(&a_is_zero, &x_not_zero);
1140    let t2 = bd.and(&b_is_zero, &x_is_one);
1141    let result_is_one = bd.or(&t1, &t2);
1142    let a_neg = bd.cmpc(Lt, a, 0.0);
1143    let b_neg = bd.cmpc(Lt, b, 0.0);
1144    let x_neg = bd.cmpc(Lt, x, 0.0);
1145    let x_gt1 = bd.cmpc(Gt, x, 1.0);
1146    let nan1 = bd.or(&a_neg, &b_neg);
1147    let nan1 = bd.or(&nan1, &x_neg);
1148    let nan1 = bd.or(&nan1, &x_gt1);
1149    let both_zero = bd.and(&a_is_zero, &b_is_zero);
1150    let nan2 = bd.or(&both_zero, &is_nan);
1151    let result_is_nan = bd.or(&nan1, &nan2);
1152
1153    // The continued fraction converges rapidly for x < (a + 1) / (a + b +
1154    // 2); otherwise I_x(a, b) = 1 - I_(1-x)(b, a).
1155    let a1 = bd.addc(a, 1.0);
1156    let ab = bd.add(a, b);
1157    let ab2 = bd.addc(&ab, 2.0);
1158    let bound = bd.div(&a1, &ab2);
1159    let converges = bd.cmp(Lt, x, &bound);
1160    let a_s = bd.select(&converges, a, b);
1161    let b_s = bd.select(&converges, b, a);
1162    let one_x = bd.csub(1.0, x);
1163    let x_s = bd.select(&converges, x, &one_x);
1164    let (a, b, x) = (a_s, b_s, x_s);
1165
1166    let num_iterations = if bd.is_f64() { 600.0 } else { 200.0 };
1167    let small = eps / 2.0;
1168    let threshold = eps / 2.0;
1169    // The partial numerator of DLMF 8.17.23 (1 for the first iteration).
1170    let numerator = |bd: &mut B, iteration: &B::F| {
1171        let rem = bd.c(2.0);
1172        let rem = bd.binary(BinaryOp::Rem, iteration, &rem);
1173        let is_even = bd.cmpc(Eq, &rem, 0.0);
1174        let is_one = bd.cmpc(Eq, iteration, 1.0);
1175        let m = bd.subc(iteration, 1.0);
1176        let half = bd.c(2.0);
1177        let m = bd.div(&m, &half);
1178        let m = bd.floor(&m);
1179        let m_is_zero = bd.cmpc(Eq, &m, 0.0);
1180        let one = bd.c(1.0);
1181        let two = bd.c(2.0);
1182        let ab = bd.add(&a, &b);
1183        let neg_ab = bd.neg(&ab);
1184        let t = bd.mul(&neg_ab, &x);
1185        let a1 = bd.add(&a, &one);
1186        let zero_numerator = bd.div(&t, &a1);
1187        let am = bd.add(&a, &m);
1188        let neg_am = bd.neg(&am);
1189        let abm = bd.add(&ab, &m);
1190        let t = bd.mul(&neg_am, &abm);
1191        let t = bd.mul(&t, &x);
1192        let two_m = bd.mul(&two, &m);
1193        let a2m = bd.add(&a, &two_m);
1194        let a2m1 = bd.add(&a2m, &one);
1195        let d = bd.mul(&a2m, &a2m1);
1196        let even = bd.div(&t, &d);
1197        let even = bd.select(&m_is_zero, &zero_numerator, &even);
1198        let bm = bd.sub(&b, &m);
1199        let t = bd.mul(&m, &bm);
1200        let t = bd.mul(&t, &x);
1201        let a2m_1 = bd.sub(&a2m, &one);
1202        let d = bd.mul(&a2m_1, &a2m);
1203        let odd = bd.div(&t, &d);
1204        let n = bd.select(&is_even, &even, &odd);
1205        bd.selc(&is_one, 1.0, &n)
1206    };
1207    let denominator = |bd: &mut B, iteration: &B::F| {
1208        let is_zero = bd.cmpc(Eq, iteration, 0.0);
1209        let one = bd.c(1.0);
1210        bd.selc(&is_zero, 0.0, &one)
1211    };
1212
1213    // The modified Lentz algorithm.
1214    let zero_iteration = bd.c(0.0);
1215    let pd = denominator(bd, &zero_iteration);
1216    let abs_pd = bd.abs(&pd);
1217    let is_small = bd.cmpc(Lt, &abs_pd, small);
1218    let h = bd.selc(&is_small, small, &pd);
1219    let iteration = bd.c(1.0);
1220    let unconverged = bd.mask(true);
1221    let d = bd.c(0.0);
1222    let init = Carry {
1223        bools: vec![unconverged],
1224        floats: vec![iteration, h.clone(), d, h],
1225    };
1226    let out = bd.while_loop(
1227        init,
1228        &mut |bd, s| {
1229            let lt = bd.cmpc(Lt, &s.floats[0], num_iterations);
1230            let lt = bd.any(&lt);
1231            let any = bd.any(&s.bools[0]);
1232            bd.and(&lt, &any)
1233        },
1234        &mut |bd, s| {
1235            let unconverged = &s.bools[0];
1236            let [iteration, c0, d0, h0] = &s.floats[..] else {
1237                unreachable!()
1238            };
1239            let pn = numerator(bd, iteration);
1240            let pd = denominator(bd, iteration);
1241            let q = bd.div(&pn, c0);
1242            let c = bd.add(&pd, &q);
1243            let small_c = bd.c(small);
1244            let abs_c = bd.abs(&c);
1245            let c_small = bd.cmp(Lt, &abs_c, &small_c);
1246            let c = bd.select(&c_small, &small_c, &c);
1247            let p = bd.mul(&pn, d0);
1248            let d = bd.add(&pd, &p);
1249            let abs_d = bd.abs(&d);
1250            let d_small = bd.cmp(Lt, &abs_d, &small_c);
1251            let d = bd.select(&d_small, &small_c, &d);
1252            let one = bd.c(1.0);
1253            let d = bd.div(&one, &d);
1254            let delta = bd.mul(&c, &d);
1255            let h = bd.mul(h0, &delta);
1256            let dm1 = bd.subc(&delta, 1.0);
1257            let dm1 = bd.abs(&dm1);
1258            let tol = bd.cmpc(Ge, &dm1, threshold);
1259            let next = bd.addc(iteration, 1.0);
1260            let unconverged_next = bd.and(unconverged, &tol);
1261            let c = bd.select(unconverged, &c, c0);
1262            let d = bd.select(unconverged, &d, d0);
1263            let h = bd.select(unconverged, &h, h0);
1264            Carry {
1265                bools: vec![unconverged_next],
1266                floats: vec![next, c, d, h],
1267            }
1268        },
1269    );
1270    let continued_fraction = &out.floats[3];
1271
1272    // For very small a, a gamma(a) = gamma(a + 1) -> 1 avoids a division by
1273    // zero.
1274    let very_small = bd.tiny() * 2.0;
1275    let lg_b = bd.lgamma(&b);
1276    let ab = bd.add(&a, &b);
1277    let lg_ab = bd.lgamma(&ab);
1278    let lbeta_small_a = bd.sub(&lg_b, &lg_ab);
1279    let lg_a = bd.lgamma(&a);
1280    let lbeta = bd.add(&lg_a, &lbeta_small_a);
1281    let neg_x = bd.neg(&x);
1282    let log1p_neg_x = bd.log1p(&neg_x);
1283    let t = bd.mul(&log1p_neg_x, &b);
1284    let t = bd.sub(&t, &lbeta_small_a);
1285    let small_factor = bd.exp(&t);
1286    let log_x = bd.log(&x);
1287    let t1 = bd.mul(&log_x, &a);
1288    let t2 = bd.mul(&log1p_neg_x, &b);
1289    let t = bd.add(&t1, &t2);
1290    let t = bd.sub(&t, &lbeta);
1291    let t = bd.exp(&t);
1292    let factor = bd.div(&t, &a);
1293    let a_small = bd.cmpc(Lt, &a, very_small);
1294    let factor = bd.select(&a_small, &small_factor, &factor);
1295    let result = bd.mul(continued_fraction, &factor);
1296    let one_minus = bd.csub(1.0, &result);
1297    let result = bd.select(&converges, &result, &one_minus);
1298    let result = bd.selc(&result_is_zero, 0.0, &result);
1299    let result = bd.selc(&result_is_one, 1.0, &result);
1300    bd.selc(&result_is_nan, f64::NAN, &result)
1301}
1302
1303// ---------------------------------------------------------------------------
1304// Dispatch
1305
1306/// Evaluates a special unary operation with a builder.
1307///
1308/// # Panics
1309///
1310/// Panics if `op` is not a special function.
1311pub fn eval_unary<B: Builder>(b: &mut B, op: UnaryOp, x: &B::F) -> B::F {
1312    match op {
1313        UnaryOp::ErfInv => erf_inv(b, x),
1314        UnaryOp::Lgamma => b.lgamma(x),
1315        UnaryOp::Digamma => b.digamma(x),
1316        UnaryOp::Erf => erf(b, x),
1317        UnaryOp::Erfc => erfc(b, x),
1318        UnaryOp::BesselI0e => bessel_i0e(b, x),
1319        UnaryOp::BesselI1e => bessel_i1e(b, x),
1320        _ => panic!("{} is not a special function", op.name()),
1321    }
1322}
1323
1324/// Evaluates a special binary operation with a builder.
1325///
1326/// # Panics
1327///
1328/// Panics if `op` is not a special function.
1329pub fn eval_binary<B: Builder>(b: &mut B, op: BinaryOp, x: &B::F, y: &B::F) -> B::F {
1330    match op {
1331        BinaryOp::Igamma => igamma(b, x, y),
1332        BinaryOp::Igammac => igammac(b, x, y),
1333        BinaryOp::IgammaGradA => igamma_grad_a(b, x, y),
1334        BinaryOp::RandomGammaGrad => random_gamma_grad(b, x, y),
1335        BinaryOp::Polygamma => polygamma(b, x, y),
1336        BinaryOp::Zeta => zeta(b, x, y),
1337        _ => panic!("{} is not a special function", op.name()),
1338    }
1339}
1340
1341/// Evaluates on scalars of type `T` (`f32` or `f64`).
1342struct Scalar<T>(std::marker::PhantomData<T>);
1343
1344impl<T: Element> Builder for Scalar<T> {
1345    type F = T;
1346    type B = bool;
1347
1348    fn is_f64(&self) -> bool {
1349        T::DTYPE == crate::DType::F64
1350    }
1351    fn constant(&mut self, v: f64) -> T {
1352        cast::<f64, T>(v)
1353    }
1354    fn unary(&mut self, op: UnaryOp, x: &T) -> T {
1355        T::unary(op, *x)
1356    }
1357    fn binary(&mut self, op: BinaryOp, x: &T, y: &T) -> T {
1358        T::binary(op, *x, *y)
1359    }
1360    fn compare(&mut self, op: CompareOp, x: &T, y: &T) -> bool {
1361        crate::ops::compare(op, *x, *y)
1362    }
1363    fn logical(&mut self, op: BinaryOp, x: &bool, y: &bool) -> bool {
1364        bool::binary(op, *x, *y)
1365    }
1366    fn not(&mut self, x: &bool) -> bool {
1367        !*x
1368    }
1369    fn select(&mut self, pred: &bool, on_true: &T, on_false: &T) -> T {
1370        if *pred { *on_true } else { *on_false }
1371    }
1372    fn mask(&mut self, v: bool) -> bool {
1373        v
1374    }
1375    fn is_finite(&mut self, x: &T) -> bool {
1376        T::is_finite(*x)
1377    }
1378    fn any(&mut self, x: &bool) -> bool {
1379        *x
1380    }
1381    fn while_loop(
1382        &mut self,
1383        init: Carry<Self>,
1384        cond: &mut dyn FnMut(&mut Self, &Carry<Self>) -> bool,
1385        body: &mut dyn FnMut(&mut Self, &Carry<Self>) -> Carry<Self>,
1386    ) -> Carry<Self> {
1387        let mut carry = init;
1388        while cond(self, &carry) {
1389            carry = body(self, &carry);
1390        }
1391        carry
1392    }
1393}
1394
1395/// A special unary function on one `f32` or `f64` value.
1396pub(crate) fn unary<T: Element>(op: UnaryOp, x: T) -> T {
1397    eval_unary(&mut Scalar::<T>(std::marker::PhantomData), op, &x)
1398}
1399
1400/// A special binary function on `f32` or `f64` values.
1401pub(crate) fn binary<T: Element>(op: BinaryOp, x: T, y: T) -> T {
1402    eval_binary(&mut Scalar::<T>(std::marker::PhantomData), op, &x, &y)
1403}
1404
1405/// The regularized incomplete beta function on `f32` or `f64` values.
1406pub(crate) fn betainc<T: Element>(a: T, b: T, x: T) -> T {
1407    regularized_incomplete_beta(&mut Scalar::<T>(std::marker::PhantomData), &a, &b, &x)
1408}
1409
1410#[cfg(test)]
1411mod tests {
1412    use super::*;
1413
1414    fn close(a: f64, e: f64, tol: f64) -> bool {
1415        (a - e).abs() <= tol * e.abs().max(1.0)
1416    }
1417
1418    #[test]
1419    fn values_match_references() {
1420        // References from scipy.special.
1421        let cases: [(UnaryOp, f64, f64); 10] = [
1422            (UnaryOp::Lgamma, 0.5, 0.572_364_942_924_700_1),
1423            (UnaryOp::Lgamma, -2.5, -0.056_243_716_497_674_05),
1424            (UnaryOp::Lgamma, 10.0, 12.801_827_480_081_469),
1425            (UnaryOp::Digamma, 1.0, -std::f64::consts::EULER_GAMMA),
1426            (UnaryOp::Digamma, -0.5, 0.036_489_973_978_576_52),
1427            (UnaryOp::Erf, 0.5, 0.520_499_877_813_046_5),
1428            (UnaryOp::Erf, -2.0, -0.995_322_265_018_952_7),
1429            (UnaryOp::Erfc, 3.0, 2.209_049_699_858_544e-5),
1430            (UnaryOp::BesselI0e, 1.0, 0.465_759_607_593_640_3),
1431            (UnaryOp::BesselI1e, -9.0, -0.127_224_983_935_891_2),
1432        ];
1433        for (op, x, e) in cases {
1434            let a = unary(op, x);
1435            assert!(close(a, e, 1e-13), "{op:?}({x}) = {a}, expected {e}");
1436            let a = f64::from(unary(op, x as f32));
1437            assert!(close(a, e, 2e-6), "{op:?}({x} f32) = {a}, expected {e}");
1438        }
1439        let cases: [(BinaryOp, f64, f64, f64); 6] = [
1440            (BinaryOp::Igamma, 2.0, 1.5, 0.442_174_599_628_925_8),
1441            (BinaryOp::Igamma, 0.5, 3.0, 0.985_694_121_564_570_4),
1442            (BinaryOp::Igammac, 3.0, 2.0, 0.676_676_416_183_063_8),
1443            (BinaryOp::Polygamma, 1.0, 2.0, 0.644_934_066_848_226_4),
1444            (BinaryOp::Zeta, 2.0, 1.0, 1.644_934_066_848_226_4),
1445            (BinaryOp::Zeta, 3.0, 2.5, 0.118_102_025_820_863_68),
1446        ];
1447        for (op, x, y, e) in cases {
1448            let a = binary(op, x, y);
1449            assert!(close(a, e, 1e-12), "{op:?}({x}, {y}) = {a}, expected {e}");
1450        }
1451        let a = betainc(2.0, 3.0, 0.4);
1452        assert!(close(a, 0.524_8, 1e-13), "{a}");
1453    }
1454
1455    #[test]
1456    fn derivatives_match_finite_differences() {
1457        for (a, x) in [(2.0, 1.5), (0.7, 3.0), (5.0, 2.0)] {
1458            let h = 1e-6;
1459            let fd = (binary(BinaryOp::Igamma, a + h, x) - binary(BinaryOp::Igamma, a - h, x))
1460                / (2.0 * h);
1461            let g = binary(BinaryOp::IgammaGradA, a, x);
1462            assert!(close(g, fd, 1e-6), "igamma_grad_a({a}, {x}) = {g}, fd {fd}");
1463            // dx/da at fixed quantile: -(dP/da) / (dP/dx).
1464            let dpdx = (-x + (a - 1.0) * f64::ln(x) - unary(UnaryOp::Lgamma, a)).exp();
1465            let r = binary(BinaryOp::RandomGammaGrad, a, x);
1466            assert!(
1467                close(r, -g / dpdx, 1e-6),
1468                "random_gamma_grad({a}, {x}) = {r}"
1469            );
1470        }
1471    }
1472
1473    #[test]
1474    fn edge_cases() {
1475        assert_eq!(unary(UnaryOp::Lgamma, f64::INFINITY), f64::INFINITY);
1476        assert_eq!(unary(UnaryOp::Lgamma, -3.0), f64::INFINITY);
1477        assert_eq!(unary(UnaryOp::Digamma, 0.0), f64::NEG_INFINITY);
1478        assert!(unary(UnaryOp::Digamma, -2.0f64).is_nan());
1479        assert_eq!(binary(BinaryOp::Igamma, 1.0, 0.0), 0.0);
1480        assert_eq!(binary(BinaryOp::Igamma, 1.0, f64::INFINITY), 1.0);
1481        assert!(binary(BinaryOp::Igamma, -1.0f64, 1.0).is_nan());
1482        assert_eq!(binary(BinaryOp::Zeta, 1.0, 2.0), f64::INFINITY);
1483        assert!(binary(BinaryOp::Polygamma, 0.5f64, 2.0).is_nan());
1484    }
1485}