Skip to main content

gauss_jacobi_quad/
lib.rs

1//! Safe Rust bindings to **GaussJacobiQuad** via the C ABI
2//! (`gauss_jacobi_rule_c` in `libgjp_cinterp`).
3//!
4//! The quadrature math stays in Fortran; this crate only marshals arrays and
5//! status codes. Build `libgjp_cinterp` with meson first, then point
6//! `GJP_CINTERP` at the `.so` (or install a `gjp_cinterp.pc`).
7//!
8//! # Example
9//!
10//! ```no_run
11//! use gauss_jacobi_quad::{gauss_jacobi, Method};
12//!
13//! let (x, w) = gauss_jacobi(32, 0.0, 0.0, Method::Auto).unwrap();
14//! assert_eq!(x.len(), 32);
15//! assert!(w.iter().all(|&wi| wi > 0.0));
16//! ```
17
18use std::ffi::{CStr, CString};
19use std::os::raw::{c_char, c_double, c_int};
20use std::ptr;
21
22/// Status codes matching `GaussJacobiQuadCInterp.h`.
23#[repr(i32)]
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub enum Status {
26    Ok = 0,
27    ErrNpts = 1,
28    ErrAlpha = 2,
29    ErrBeta = 3,
30    ErrMethod = 4,
31    ErrBogaertAb = 5,
32    ErrBogaertN = 6,
33    Unknown = -1,
34}
35
36impl From<c_int> for Status {
37    fn from(v: c_int) -> Self {
38        match v {
39            0 => Status::Ok,
40            1 => Status::ErrNpts,
41            2 => Status::ErrAlpha,
42            3 => Status::ErrBeta,
43            4 => Status::ErrMethod,
44            5 => Status::ErrBogaertAb,
45            6 => Status::ErrBogaertN,
46            _ => Status::Unknown,
47        }
48    }
49}
50
51impl Status {
52    pub fn message(self) -> &'static str {
53        match self {
54            Status::Ok => "ok",
55            Status::ErrNpts => "npts must be positive",
56            Status::ErrAlpha => "alpha must be greater than -1",
57            Status::ErrBeta => "beta must be greater than -1",
58            Status::ErrMethod => "unknown method",
59            Status::ErrBogaertAb => "bogaert requires alpha=beta=0",
60            Status::ErrBogaertN => "bogaert requires n >= 21",
61            Status::Unknown => "unknown status",
62        }
63    }
64}
65
66/// Error from the C library or argument validation.
67#[derive(Debug, thiserror::Error)]
68pub enum Error {
69    #[error("gauss_jacobi_rule_c: {status:?} ({msg}) method={method:?}")]
70    Library {
71        status: Status,
72        msg: &'static str,
73        method: Option<String>,
74    },
75    #[error("invalid method string (interior NUL)")]
76    Nul(#[from] std::ffi::NulError),
77}
78
79/// Method selection for [`gauss_jacobi`].
80#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
81pub enum Method {
82    /// `select_method_auto` policy (empty / `"auto"`).
83    #[default]
84    Auto,
85    Rec,
86    Gw,
87    Algo665,
88    Algo665Dc,
89    Sturm,
90    Glr,
91    Bogaert,
92}
93
94impl Method {
95    pub fn as_c_str(self) -> Option<&'static str> {
96        match self {
97            Method::Auto => None,
98            Method::Rec => Some("rec"),
99            Method::Gw => Some("gw"),
100            Method::Algo665 => Some("algo665"),
101            Method::Algo665Dc => Some("algo665_dc"),
102            Method::Sturm => Some("sturm"),
103            Method::Glr => Some("glr"),
104            Method::Bogaert => Some("bogaert"),
105        }
106    }
107}
108
109#[link(name = "gjp_cinterp")]
110extern "C" {
111    fn gauss_jacobi_rule_c(
112        npts: c_int,
113        alpha: c_double,
114        beta: c_double,
115        x: *mut c_double,
116        wts: *mut c_double,
117        method: *const c_char,
118    ) -> c_int;
119
120    fn gjp_status_string(status: c_int) -> *const c_char;
121}
122
123/// Human-readable status from the C library (static C string).
124pub fn status_string(status: Status) -> String {
125    unsafe {
126        let p = gjp_status_string(status as c_int);
127        if p.is_null() {
128            return status.message().to_string();
129        }
130        CStr::from_ptr(p).to_string_lossy().into_owned()
131    }
132}
133
134/// Compute Gauss–Jacobi nodes and weights.
135///
136/// Returns `(nodes, weights)` of length `npts`, ordered as produced by the
137/// library (typically ascending nodes).
138pub fn gauss_jacobi(
139    npts: usize,
140    alpha: f64,
141    beta: f64,
142    method: Method,
143) -> Result<(Vec<f64>, Vec<f64>), Error> {
144    if npts == 0 || npts > i32::MAX as usize {
145        return Err(Error::Library {
146            status: Status::ErrNpts,
147            msg: Status::ErrNpts.message(),
148            method: method.as_c_str().map(str::to_string),
149        });
150    }
151    let mut x = vec![0.0_f64; npts];
152    let mut w = vec![0.0_f64; npts];
153    let c_method: Option<CString> = match method.as_c_str() {
154        None => None,
155        Some(s) => Some(CString::new(s)?),
156    };
157    let method_ptr = c_method
158        .as_ref()
159        .map(|c| c.as_ptr())
160        .unwrap_or(ptr::null());
161
162    let st = unsafe {
163        gauss_jacobi_rule_c(
164            npts as c_int,
165            alpha,
166            beta,
167            x.as_mut_ptr(),
168            w.as_mut_ptr(),
169            method_ptr,
170        )
171    };
172    let status = Status::from(st);
173    if status != Status::Ok {
174        return Err(Error::Library {
175            status,
176            msg: status.message(),
177            method: method.as_c_str().map(str::to_string),
178        });
179    }
180    Ok((x, w))
181}
182
183/// Force a method by raw C string (e.g. `"sturm_caf"` is rejected by C surface;
184/// use Fortran for CAF). Empty / `"auto"` select the policy.
185pub fn gauss_jacobi_method_str(
186    npts: usize,
187    alpha: f64,
188    beta: f64,
189    method: &str,
190) -> Result<(Vec<f64>, Vec<f64>), Error> {
191    if npts == 0 || npts > i32::MAX as usize {
192        return Err(Error::Library {
193            status: Status::ErrNpts,
194            msg: Status::ErrNpts.message(),
195            method: Some(method.to_string()),
196        });
197    }
198    let mut x = vec![0.0_f64; npts];
199    let mut w = vec![0.0_f64; npts];
200    let c_method = if method.is_empty() || method == "auto" {
201        None
202    } else {
203        Some(CString::new(method)?)
204    };
205    let method_ptr = c_method
206        .as_ref()
207        .map(|c| c.as_ptr())
208        .unwrap_or(ptr::null());
209    let st = unsafe {
210        gauss_jacobi_rule_c(
211            npts as c_int,
212            alpha,
213            beta,
214            x.as_mut_ptr(),
215            w.as_mut_ptr(),
216            method_ptr,
217        )
218    };
219    let status = Status::from(st);
220    if status != Status::Ok {
221        return Err(Error::Library {
222            status,
223            msg: status.message(),
224            method: Some(method.to_string()),
225        });
226    }
227    Ok((x, w))
228}
229
230#[cfg(test)]
231mod tests {
232    use super::*;
233
234    #[test]
235    fn auto_legendre_positive_weights() {
236        let (x, w) = gauss_jacobi(32, 0.0, 0.0, Method::Auto).expect("auto");
237        assert_eq!(x.len(), 32);
238        assert!(w.iter().all(|&wi| wi > 0.0 && wi.is_finite()));
239        assert!(x.iter().all(|&xi| xi > -1.0 && xi < 1.0 && xi.is_finite()));
240        let s: f64 = w.iter().sum();
241        assert!((s - 2.0).abs() < 1e-12);
242    }
243
244    #[test]
245    fn glr_matches_algo665() {
246        let (xg, wg) = gauss_jacobi(40, 0.5, 0.5, Method::Glr).unwrap();
247        let (xa, wa) = gauss_jacobi(40, 0.5, 0.5, Method::Algo665).unwrap();
248        let xg = xg;
249        let xa = xa;
250        // sort for comparison
251        let mut ig: Vec<_> = (0..xg.len()).collect();
252        ig.sort_by(|&i, &j| xg[i].partial_cmp(&xg[j]).unwrap());
253        let mut ia: Vec<_> = (0..xa.len()).collect();
254        ia.sort_by(|&i, &j| xa[i].partial_cmp(&xa[j]).unwrap());
255        for k in 0..xg.len() {
256            assert!((xg[ig[k]] - xa[ia[k]]).abs() < 1e-12);
257            assert!((wg[ig[k]] - wa[ia[k]]).abs() < 1e-11);
258        }
259    }
260
261    #[test]
262    fn bogaert_non_legendre_errors() {
263        let err = gauss_jacobi(32, 0.5, 0.0, Method::Bogaert).unwrap_err();
264        match err {
265            Error::Library { status, .. } => assert_eq!(status, Status::ErrBogaertAb),
266            _ => panic!("unexpected"),
267        }
268    }
269}