Skip to main content

aocl_data_analytics/
lib.rs

1//! Safe wrappers for AOCL-DA (Data Analytics).
2
3#![allow(
4    clippy::too_many_arguments,
5    reason = "wrappers mirror the C API's argument lists"
6)]
7#![warn(missing_debug_implementations)]
8#![cfg_attr(docsrs, feature(doc_cfg))]
9
10use aocl_data_analytics_sys as sys;
11pub use aocl_error::{Error, Result};
12use aocl_types::sealed::Sealed;
13pub use aocl_types::Layout;
14
15/// Validate a dense `rows x cols` matrix argument with leading dimension `ld` in `layout`: `ld` at least the minor extent and the buffer
16/// at least `(major - 1) * ld + minor` elements. The library does not check (access violation one element short, AOCL 6.0.68).
17fn check_dense(
18    name: &str,
19    what: &str,
20    layout: Layout,
21    rows: usize,
22    cols: usize,
23    ld: usize,
24    len: usize,
25) -> Result<()> {
26    if rows == 0 || cols == 0 {
27        return Ok(());
28    }
29    let (major, minor) = match layout {
30        Layout::RowMajor => (rows, cols),
31        Layout::ColMajor => (cols, rows),
32    };
33    if ld < minor {
34        return Err(Error::InvalidArgument(format!(
35            "{name}: {what} has ld={ld}, the {rows}x{cols} matrix needs at least {minor}"
36        )));
37    }
38    let need = (major - 1) * ld + minor;
39    if len < need {
40        return Err(Error::InvalidArgument(format!(
41            "{name}: {what}.len()={len}, the {rows}x{cols} matrix with ld={ld} needs {need}"
42        )));
43    }
44    Ok(())
45}
46
47fn layout_raw(l: Layout) -> sys::da_order {
48    match l {
49        Layout::RowMajor => sys::da_order__row_major,
50        Layout::ColMajor => sys::da_order__column_major,
51    }
52}
53
54/// Reduction axis: per-column, per-row, or global.
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
56pub enum Axis {
57    /// Reduce each column down to a single value (output length = n_cols).
58    Col,
59    /// Reduce each row down to a single value (output length = n_rows).
60    Row,
61    /// Reduce all elements to a single value (output length = 1).
62    All,
63}
64
65impl Axis {
66    fn raw(self) -> sys::da_axis {
67        match self {
68            Axis::Col => sys::da_axis__da_axis_col,
69            Axis::Row => sys::da_axis__da_axis_row,
70            Axis::All => sys::da_axis__da_axis_all,
71        }
72    }
73
74    fn output_len(self, n_rows: usize, n_cols: usize) -> usize {
75        match self {
76            Axis::Col => n_cols,
77            Axis::Row => n_rows,
78            Axis::All => 1,
79        }
80    }
81}
82
83fn check_status(component: &'static str, status: sys::da_status) -> Result<()> {
84    if status == sys::da_status__da_status_success {
85        return Ok(());
86    }
87    let message = match status {
88        s if s == sys::da_status__da_status_internal_error => "internal error",
89        s if s == sys::da_status__da_status_memory_error => "memory error",
90        s if s == sys::da_status__da_status_invalid_pointer => "invalid pointer",
91        s if s == sys::da_status__da_status_invalid_input => "invalid input",
92        s if s == sys::da_status__da_status_not_implemented => "not implemented",
93        s if s == sys::da_status__da_status_overflow => "overflow",
94        s if s == sys::da_status__da_status_invalid_leading_dimension => {
95            "invalid leading dimension"
96        }
97        s if s == sys::da_status__da_status_negative_data => "negative data",
98        s if s == sys::da_status__da_status_invalid_array_dimension => "invalid array dimension",
99        s if s == sys::da_status__da_status_no_data => "no data",
100        s if s == sys::da_status__da_status_wrong_type => "wrong type",
101        s if s == sys::da_status__da_status_invalid_handle_type => "invalid handle type",
102        s if s == sys::da_status__da_status_handle_not_initialized => "handle not initialized",
103        s if s == sys::da_status__da_status_store_not_initialized => "store not initialized",
104        s if s == sys::da_status__da_status_invalid_option => "invalid option",
105        s if s == sys::da_status__da_status_incompatible_options => "incompatible options",
106        s if s == sys::da_status__da_status_operation_failed => "operation failed",
107        s if s == sys::da_status__da_status_unknown_query => "unknown query",
108        s if s == sys::da_status__da_status_incorrect_output => "incorrect output",
109        s if s == sys::da_status__da_status_maxit => "max iterations reached",
110        s if s == sys::da_status__da_status_maxtime => "max time reached",
111        s if s == sys::da_status__da_status_numerical_difficulties => "numerical difficulties",
112        s if s == sys::da_status__da_status_bad_derivatives => "bad derivatives",
113        s if s == sys::da_status__da_status_optimization_usrstop => "optimisation user stop",
114        _ => "unknown DA status",
115    }
116    .to_string();
117    Err(Error::Status {
118        component,
119        code: status as i64,
120        message,
121    })
122}
123
124fn check_matrix(
125    name: &str,
126    layout: Layout,
127    n_rows: usize,
128    n_cols: usize,
129    ldx: usize,
130    x_len: usize,
131) -> Result<()> {
132    if n_rows == 0 || n_cols == 0 {
133        return Ok(());
134    }
135    let (lead, trail) = match layout {
136        Layout::RowMajor => (n_rows, n_cols),
137        Layout::ColMajor => (n_cols, n_rows),
138    };
139    if ldx < trail {
140        return Err(Error::InvalidArgument(format!(
141            "{name}: ldx={ldx} < {trail}"
142        )));
143    }
144    let needed = (lead - 1) * ldx + trail;
145    if x_len < needed {
146        return Err(Error::InvalidArgument(format!(
147            "{name}: slice length {x_len} too small (need {needed})"
148        )));
149    }
150    Ok(())
151}
152
153/// Method used for quantile computation. Each variant matches one of
154/// the nine standard quantile types (Hyndman & Fan 1996); types 6 and 7
155/// are the most commonly used.
156#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
157pub enum QuantileType {
158    Type1,
159    Type2,
160    Type3,
161    Type4,
162    Type5,
163    Type6,
164    Type7,
165    Type8,
166    Type9,
167}
168
169impl QuantileType {
170    fn raw(self) -> sys::da_quantile_type {
171        match self {
172            QuantileType::Type1 => sys::da_quantile_type__da_quantile_type_1,
173            QuantileType::Type2 => sys::da_quantile_type__da_quantile_type_2,
174            QuantileType::Type3 => sys::da_quantile_type__da_quantile_type_3,
175            QuantileType::Type4 => sys::da_quantile_type__da_quantile_type_4,
176            QuantileType::Type5 => sys::da_quantile_type__da_quantile_type_5,
177            QuantileType::Type6 => sys::da_quantile_type__da_quantile_type_6,
178            QuantileType::Type7 => sys::da_quantile_type__da_quantile_type_7,
179            QuantileType::Type8 => sys::da_quantile_type__da_quantile_type_8,
180            QuantileType::Type9 => sys::da_quantile_type__da_quantile_type_9,
181        }
182    }
183}
184
185/// Scalar element type usable with the wrapped DA routines.
186pub trait Scalar: Copy + Sized + Sealed {
187    /// Compute means along `axis` for an `n_rows × n_cols` matrix.
188    fn mean(
189        layout: Layout,
190        axis: Axis,
191        n_rows: usize,
192        n_cols: usize,
193        x: &[Self],
194        ldx: usize,
195        out: &mut [Self],
196    ) -> Result<()>;
197
198    /// Compute means and variances along `axis`.
199    ///
200    /// `dof` selects the variance divisor:
201    /// - `dof < 0` — divide by `n` (number of observations).
202    /// - `dof == 0` — divide by `n - 1` (Bessel-corrected, unbiased).
203    /// - `dof > 0` — divide by the literal value of `dof`.
204    fn variance(
205        layout: Layout,
206        axis: Axis,
207        n_rows: usize,
208        n_cols: usize,
209        x: &[Self],
210        ldx: usize,
211        dof: i64,
212        mean_out: &mut [Self],
213        variance_out: &mut [Self],
214    ) -> Result<()>;
215
216    /// Geometric mean. Requires non-negative data.
217    fn geometric_mean(
218        layout: Layout,
219        axis: Axis,
220        n_rows: usize,
221        n_cols: usize,
222        x: &[Self],
223        ldx: usize,
224        out: &mut [Self],
225    ) -> Result<()>;
226
227    /// Harmonic mean.
228    fn harmonic_mean(
229        layout: Layout,
230        axis: Axis,
231        n_rows: usize,
232        n_cols: usize,
233        x: &[Self],
234        ldx: usize,
235        out: &mut [Self],
236    ) -> Result<()>;
237
238    /// Mean, variance, and skewness together.
239    fn skewness(
240        layout: Layout,
241        axis: Axis,
242        n_rows: usize,
243        n_cols: usize,
244        x: &[Self],
245        ldx: usize,
246        mean_out: &mut [Self],
247        variance_out: &mut [Self],
248        skew_out: &mut [Self],
249    ) -> Result<()>;
250
251    /// Mean, variance, and excess kurtosis together (Fisher convention,
252    /// so a normal distribution scores zero).
253    fn kurtosis(
254        layout: Layout,
255        axis: Axis,
256        n_rows: usize,
257        n_cols: usize,
258        x: &[Self],
259        ldx: usize,
260        mean_out: &mut [Self],
261        variance_out: &mut [Self],
262        kurtosis_out: &mut [Self],
263    ) -> Result<()>;
264
265    /// `k`-th central moment. If `mean_out` already holds means and
266    /// `use_precomputed_mean` is true, those means are used; otherwise
267    /// they are computed and stored.
268    fn moment(
269        layout: Layout,
270        axis: Axis,
271        n_rows: usize,
272        n_cols: usize,
273        x: &[Self],
274        ldx: usize,
275        k: i64,
276        use_precomputed_mean: bool,
277        mean_out: &mut [Self],
278        moment_out: &mut [Self],
279    ) -> Result<()>;
280
281    /// Quantile of the data along `axis`. `q` ∈ [0, 1].
282    fn quantile(
283        layout: Layout,
284        axis: Axis,
285        n_rows: usize,
286        n_cols: usize,
287        x: &[Self],
288        ldx: usize,
289        q: Self,
290        quantile_out: &mut [Self],
291        qtype: QuantileType,
292    ) -> Result<()>;
293
294    /// Min, lower hinge (25th percentile), median, upper hinge
295    /// (75th percentile), max — Tukey's "five-number summary".
296    fn five_point_summary(
297        layout: Layout,
298        axis: Axis,
299        n_rows: usize,
300        n_cols: usize,
301        x: &[Self],
302        ldx: usize,
303        min: &mut [Self],
304        lower: &mut [Self],
305        median: &mut [Self],
306        upper: &mut [Self],
307        max: &mut [Self],
308    ) -> Result<()>;
309
310    /// Compute the `n_cols × n_cols` covariance matrix (rows are
311    /// observations). `dof` follows the same convention as `variance`.
312    fn covariance_matrix(
313        layout: Layout,
314        n_rows: usize,
315        n_cols: usize,
316        x: &[Self],
317        ldx: usize,
318        dof: i64,
319        cov: &mut [Self],
320        ldcov: usize,
321    ) -> Result<()>;
322
323    /// Compute the `n_cols × n_cols` correlation matrix (rows are
324    /// observations).
325    fn correlation_matrix(
326        layout: Layout,
327        n_rows: usize,
328        n_cols: usize,
329        x: &[Self],
330        ldx: usize,
331        corr: &mut [Self],
332        ldcorr: usize,
333    ) -> Result<()>;
334}
335
336macro_rules! impl_scalar {
337    (
338        $t:ty,
339        mean = $mean:ident,
340        variance = $variance:ident,
341        geometric_mean = $gmean:ident,
342        harmonic_mean = $hmean:ident,
343        skewness = $skew:ident,
344        kurtosis = $kurt:ident,
345        moment = $moment:ident,
346        quantile = $quant:ident,
347        five_point_summary = $fps:ident,
348        covariance_matrix = $cov:ident,
349        correlation_matrix = $corr:ident
350    ) => {
351        impl Scalar for $t {
352            fn mean(
353                layout: Layout,
354                axis: Axis,
355                n_rows: usize,
356                n_cols: usize,
357                x: &[Self],
358                ldx: usize,
359                out: &mut [Self],
360            ) -> Result<()> {
361                check_matrix("mean: X", layout, n_rows, n_cols, ldx, x.len())?;
362                let need = axis.output_len(n_rows, n_cols);
363                if out.len() < need {
364                    return Err(Error::InvalidArgument(format!(
365                        "mean: out length {} < required {need}",
366                        out.len()
367                    )));
368                }
369                let status = unsafe {
370                    sys::$mean(
371                        layout_raw(layout),
372                        axis.raw(),
373                        n_rows as sys::da_int,
374                        n_cols as sys::da_int,
375                        x.as_ptr(),
376                        ldx as sys::da_int,
377                        out.as_mut_ptr(),
378                    )
379                };
380                check_status("data-analytics", status)
381            }
382
383            fn variance(
384                layout: Layout,
385                axis: Axis,
386                n_rows: usize,
387                n_cols: usize,
388                x: &[Self],
389                ldx: usize,
390                dof: i64,
391                mean_out: &mut [Self],
392                variance_out: &mut [Self],
393            ) -> Result<()> {
394                check_matrix("variance: X", layout, n_rows, n_cols, ldx, x.len())?;
395                let need = axis.output_len(n_rows, n_cols);
396                if mean_out.len() < need || variance_out.len() < need {
397                    return Err(Error::InvalidArgument(format!(
398                        "variance: outputs must hold {need} elements"
399                    )));
400                }
401                let status = unsafe {
402                    sys::$variance(
403                        layout_raw(layout),
404                        axis.raw(),
405                        n_rows as sys::da_int,
406                        n_cols as sys::da_int,
407                        x.as_ptr(),
408                        ldx as sys::da_int,
409                        dof as sys::da_int,
410                        mean_out.as_mut_ptr(),
411                        variance_out.as_mut_ptr(),
412                    )
413                };
414                check_status("data-analytics", status)
415            }
416
417            fn geometric_mean(
418                layout: Layout,
419                axis: Axis,
420                n_rows: usize,
421                n_cols: usize,
422                x: &[Self],
423                ldx: usize,
424                out: &mut [Self],
425            ) -> Result<()> {
426                check_matrix("geometric_mean: X", layout, n_rows, n_cols, ldx, x.len())?;
427                let need = axis.output_len(n_rows, n_cols);
428                if out.len() < need {
429                    return Err(Error::InvalidArgument(format!(
430                        "geometric_mean: out length {} < required {need}",
431                        out.len()
432                    )));
433                }
434                let status = unsafe {
435                    sys::$gmean(
436                        layout_raw(layout),
437                        axis.raw(),
438                        n_rows as sys::da_int,
439                        n_cols as sys::da_int,
440                        x.as_ptr(),
441                        ldx as sys::da_int,
442                        out.as_mut_ptr(),
443                    )
444                };
445                check_status("data-analytics", status)
446            }
447
448            fn harmonic_mean(
449                layout: Layout,
450                axis: Axis,
451                n_rows: usize,
452                n_cols: usize,
453                x: &[Self],
454                ldx: usize,
455                out: &mut [Self],
456            ) -> Result<()> {
457                check_matrix("harmonic_mean: X", layout, n_rows, n_cols, ldx, x.len())?;
458                let need = axis.output_len(n_rows, n_cols);
459                if out.len() < need {
460                    return Err(Error::InvalidArgument(format!(
461                        "harmonic_mean: out length {} < required {need}",
462                        out.len()
463                    )));
464                }
465                let status = unsafe {
466                    sys::$hmean(
467                        layout_raw(layout),
468                        axis.raw(),
469                        n_rows as sys::da_int,
470                        n_cols as sys::da_int,
471                        x.as_ptr(),
472                        ldx as sys::da_int,
473                        out.as_mut_ptr(),
474                    )
475                };
476                check_status("data-analytics", status)
477            }
478
479            fn skewness(
480                layout: Layout,
481                axis: Axis,
482                n_rows: usize,
483                n_cols: usize,
484                x: &[Self],
485                ldx: usize,
486                mean_out: &mut [Self],
487                variance_out: &mut [Self],
488                skew_out: &mut [Self],
489            ) -> Result<()> {
490                check_matrix("skewness: X", layout, n_rows, n_cols, ldx, x.len())?;
491                let need = axis.output_len(n_rows, n_cols);
492                if mean_out.len() < need || variance_out.len() < need || skew_out.len() < need {
493                    return Err(Error::InvalidArgument(format!(
494                        "skewness: outputs must hold {need} elements"
495                    )));
496                }
497                let status = unsafe {
498                    sys::$skew(
499                        layout_raw(layout),
500                        axis.raw(),
501                        n_rows as sys::da_int,
502                        n_cols as sys::da_int,
503                        x.as_ptr(),
504                        ldx as sys::da_int,
505                        mean_out.as_mut_ptr(),
506                        variance_out.as_mut_ptr(),
507                        skew_out.as_mut_ptr(),
508                    )
509                };
510                check_status("data-analytics", status)
511            }
512
513            fn kurtosis(
514                layout: Layout,
515                axis: Axis,
516                n_rows: usize,
517                n_cols: usize,
518                x: &[Self],
519                ldx: usize,
520                mean_out: &mut [Self],
521                variance_out: &mut [Self],
522                kurtosis_out: &mut [Self],
523            ) -> Result<()> {
524                check_matrix("kurtosis: X", layout, n_rows, n_cols, ldx, x.len())?;
525                let need = axis.output_len(n_rows, n_cols);
526                if mean_out.len() < need || variance_out.len() < need || kurtosis_out.len() < need {
527                    return Err(Error::InvalidArgument(format!(
528                        "kurtosis: outputs must hold {need} elements"
529                    )));
530                }
531                let status = unsafe {
532                    sys::$kurt(
533                        layout_raw(layout),
534                        axis.raw(),
535                        n_rows as sys::da_int,
536                        n_cols as sys::da_int,
537                        x.as_ptr(),
538                        ldx as sys::da_int,
539                        mean_out.as_mut_ptr(),
540                        variance_out.as_mut_ptr(),
541                        kurtosis_out.as_mut_ptr(),
542                    )
543                };
544                check_status("data-analytics", status)
545            }
546
547            fn moment(
548                layout: Layout,
549                axis: Axis,
550                n_rows: usize,
551                n_cols: usize,
552                x: &[Self],
553                ldx: usize,
554                k: i64,
555                use_precomputed_mean: bool,
556                mean_out: &mut [Self],
557                moment_out: &mut [Self],
558            ) -> Result<()> {
559                check_matrix("moment: X", layout, n_rows, n_cols, ldx, x.len())?;
560                let need = axis.output_len(n_rows, n_cols);
561                if mean_out.len() < need || moment_out.len() < need {
562                    return Err(Error::InvalidArgument(format!(
563                        "moment: outputs must hold {need} elements"
564                    )));
565                }
566                let status = unsafe {
567                    sys::$moment(
568                        layout_raw(layout),
569                        axis.raw(),
570                        n_rows as sys::da_int,
571                        n_cols as sys::da_int,
572                        x.as_ptr(),
573                        ldx as sys::da_int,
574                        k as sys::da_int,
575                        if use_precomputed_mean { 1 } else { 0 } as sys::da_int,
576                        mean_out.as_mut_ptr(),
577                        moment_out.as_mut_ptr(),
578                    )
579                };
580                check_status("data-analytics", status)
581            }
582
583            fn quantile(
584                layout: Layout,
585                axis: Axis,
586                n_rows: usize,
587                n_cols: usize,
588                x: &[Self],
589                ldx: usize,
590                q: Self,
591                quantile_out: &mut [Self],
592                qtype: QuantileType,
593            ) -> Result<()> {
594                check_matrix("quantile: X", layout, n_rows, n_cols, ldx, x.len())?;
595                let need = axis.output_len(n_rows, n_cols);
596                if quantile_out.len() < need {
597                    return Err(Error::InvalidArgument(format!(
598                        "quantile: out length {} < required {need}",
599                        quantile_out.len()
600                    )));
601                }
602                let status = unsafe {
603                    sys::$quant(
604                        layout_raw(layout),
605                        axis.raw(),
606                        n_rows as sys::da_int,
607                        n_cols as sys::da_int,
608                        x.as_ptr(),
609                        ldx as sys::da_int,
610                        &q,
611                        1,
612                        quantile_out.as_mut_ptr(),
613                        qtype.raw(),
614                    )
615                };
616                check_status("data-analytics", status)
617            }
618
619            fn five_point_summary(
620                layout: Layout,
621                axis: Axis,
622                n_rows: usize,
623                n_cols: usize,
624                x: &[Self],
625                ldx: usize,
626                min: &mut [Self],
627                lower: &mut [Self],
628                median: &mut [Self],
629                upper: &mut [Self],
630                max: &mut [Self],
631            ) -> Result<()> {
632                check_matrix(
633                    "five_point_summary: X",
634                    layout,
635                    n_rows,
636                    n_cols,
637                    ldx,
638                    x.len(),
639                )?;
640                let need = axis.output_len(n_rows, n_cols);
641                if min.len() < need
642                    || lower.len() < need
643                    || median.len() < need
644                    || upper.len() < need
645                    || max.len() < need
646                {
647                    return Err(Error::InvalidArgument(format!(
648                        "five_point_summary: each output must hold {need} elements"
649                    )));
650                }
651                let status = unsafe {
652                    sys::$fps(
653                        layout_raw(layout),
654                        axis.raw(),
655                        n_rows as sys::da_int,
656                        n_cols as sys::da_int,
657                        x.as_ptr(),
658                        ldx as sys::da_int,
659                        min.as_mut_ptr(),
660                        lower.as_mut_ptr(),
661                        median.as_mut_ptr(),
662                        upper.as_mut_ptr(),
663                        max.as_mut_ptr(),
664                    )
665                };
666                check_status("data-analytics", status)
667            }
668
669            fn covariance_matrix(
670                layout: Layout,
671                n_rows: usize,
672                n_cols: usize,
673                x: &[Self],
674                ldx: usize,
675                dof: i64,
676                cov: &mut [Self],
677                ldcov: usize,
678            ) -> Result<()> {
679                check_matrix("covariance_matrix: X", layout, n_rows, n_cols, ldx, x.len())?;
680                if ldcov < n_cols {
681                    return Err(Error::InvalidArgument(format!(
682                        "covariance_matrix: ldcov={ldcov} < n_cols={n_cols}"
683                    )));
684                }
685                if cov.len() < n_cols * ldcov {
686                    return Err(Error::InvalidArgument(format!(
687                        "covariance_matrix: cov length {} < n_cols·ldcov = {}",
688                        cov.len(),
689                        n_cols * ldcov
690                    )));
691                }
692                let status = unsafe {
693                    sys::$cov(
694                        layout_raw(layout),
695                        n_rows as sys::da_int,
696                        n_cols as sys::da_int,
697                        x.as_ptr(),
698                        ldx as sys::da_int,
699                        dof as sys::da_int,
700                        cov.as_mut_ptr(),
701                        ldcov as sys::da_int,
702                        0, // assume_centered = false: subtract the column means, as before AOCL 5.3 added the argument
703                    )
704                };
705                check_status("data-analytics", status)
706            }
707
708            fn correlation_matrix(
709                layout: Layout,
710                n_rows: usize,
711                n_cols: usize,
712                x: &[Self],
713                ldx: usize,
714                corr: &mut [Self],
715                ldcorr: usize,
716            ) -> Result<()> {
717                check_matrix(
718                    "correlation_matrix: X",
719                    layout,
720                    n_rows,
721                    n_cols,
722                    ldx,
723                    x.len(),
724                )?;
725                if ldcorr < n_cols {
726                    return Err(Error::InvalidArgument(format!(
727                        "correlation_matrix: ldcorr={ldcorr} < n_cols={n_cols}"
728                    )));
729                }
730                if corr.len() < n_cols * ldcorr {
731                    return Err(Error::InvalidArgument(format!(
732                        "correlation_matrix: corr length {} < n_cols·ldcorr = {}",
733                        corr.len(),
734                        n_cols * ldcorr
735                    )));
736                }
737                let status = unsafe {
738                    sys::$corr(
739                        layout_raw(layout),
740                        n_rows as sys::da_int,
741                        n_cols as sys::da_int,
742                        x.as_ptr(),
743                        ldx as sys::da_int,
744                        corr.as_mut_ptr(),
745                        ldcorr as sys::da_int,
746                    )
747                };
748                check_status("data-analytics", status)
749            }
750        }
751    };
752}
753
754impl_scalar!(
755    f32,
756    mean = da_mean_s,
757    variance = da_variance_s,
758    geometric_mean = da_geometric_mean_s,
759    harmonic_mean = da_harmonic_mean_s,
760    skewness = da_skewness_s,
761    kurtosis = da_kurtosis_s,
762    moment = da_moment_s,
763    quantile = da_quantile_s,
764    five_point_summary = da_five_point_summary_s,
765    covariance_matrix = da_covariance_matrix_s,
766    correlation_matrix = da_correlation_matrix_s
767);
768impl_scalar!(
769    f64,
770    mean = da_mean_d,
771    variance = da_variance_d,
772    geometric_mean = da_geometric_mean_d,
773    harmonic_mean = da_harmonic_mean_d,
774    skewness = da_skewness_d,
775    kurtosis = da_kurtosis_d,
776    moment = da_moment_d,
777    quantile = da_quantile_d,
778    five_point_summary = da_five_point_summary_d,
779    covariance_matrix = da_covariance_matrix_d,
780    correlation_matrix = da_correlation_matrix_d
781);
782
783/// Compute the mean of a tightly-packed row-major matrix along `axis`.
784pub fn mean<T: Scalar>(
785    axis: Axis,
786    n_rows: usize,
787    n_cols: usize,
788    x: &[T],
789    out: &mut [T],
790) -> Result<()> {
791    T::mean(Layout::RowMajor, axis, n_rows, n_cols, x, n_cols, out)
792}
793
794/// Compute mean and variance of a tightly-packed row-major matrix along `axis`.
795pub fn variance<T: Scalar>(
796    axis: Axis,
797    n_rows: usize,
798    n_cols: usize,
799    x: &[T],
800    dof: i64,
801    mean_out: &mut [T],
802    variance_out: &mut [T],
803) -> Result<()> {
804    T::variance(
805        Layout::RowMajor,
806        axis,
807        n_rows,
808        n_cols,
809        x,
810        n_cols,
811        dof,
812        mean_out,
813        variance_out,
814    )
815}
816
817/// Compute the geometric mean along `axis` for a tightly-packed
818/// row-major matrix. All entries must be non-negative.
819pub fn geometric_mean<T: Scalar>(
820    axis: Axis,
821    n_rows: usize,
822    n_cols: usize,
823    x: &[T],
824    out: &mut [T],
825) -> Result<()> {
826    T::geometric_mean(Layout::RowMajor, axis, n_rows, n_cols, x, n_cols, out)
827}
828
829/// Compute the harmonic mean along `axis` for a tightly-packed
830/// row-major matrix.
831pub fn harmonic_mean<T: Scalar>(
832    axis: Axis,
833    n_rows: usize,
834    n_cols: usize,
835    x: &[T],
836    out: &mut [T],
837) -> Result<()> {
838    T::harmonic_mean(Layout::RowMajor, axis, n_rows, n_cols, x, n_cols, out)
839}
840
841/// Compute means, variances, and Fisher–Pearson skewness along `axis`.
842pub fn skewness<T: Scalar>(
843    axis: Axis,
844    n_rows: usize,
845    n_cols: usize,
846    x: &[T],
847    mean_out: &mut [T],
848    variance_out: &mut [T],
849    skew_out: &mut [T],
850) -> Result<()> {
851    T::skewness(
852        Layout::RowMajor,
853        axis,
854        n_rows,
855        n_cols,
856        x,
857        n_cols,
858        mean_out,
859        variance_out,
860        skew_out,
861    )
862}
863
864/// Compute means, variances, and excess kurtosis (Fisher convention,
865/// so a normal distribution scores zero) along `axis`.
866pub fn kurtosis<T: Scalar>(
867    axis: Axis,
868    n_rows: usize,
869    n_cols: usize,
870    x: &[T],
871    mean_out: &mut [T],
872    variance_out: &mut [T],
873    kurtosis_out: &mut [T],
874) -> Result<()> {
875    T::kurtosis(
876        Layout::RowMajor,
877        axis,
878        n_rows,
879        n_cols,
880        x,
881        n_cols,
882        mean_out,
883        variance_out,
884        kurtosis_out,
885    )
886}
887
888/// Compute the `k`-th central moment along `axis`. If `mean_out` already
889/// holds means and `use_precomputed_mean` is `true`, those are used
890/// directly; otherwise means are computed and stored.
891pub fn moment<T: Scalar>(
892    axis: Axis,
893    n_rows: usize,
894    n_cols: usize,
895    x: &[T],
896    k: i64,
897    use_precomputed_mean: bool,
898    mean_out: &mut [T],
899    moment_out: &mut [T],
900) -> Result<()> {
901    T::moment(
902        Layout::RowMajor,
903        axis,
904        n_rows,
905        n_cols,
906        x,
907        n_cols,
908        k,
909        use_precomputed_mean,
910        mean_out,
911        moment_out,
912    )
913}
914
915/// Compute the `q`-th quantile along `axis` (`q` ∈ [0, 1]). The
916/// `qtype` selects one of the nine standard quantile formulae;
917/// `QuantileType::Type7` matches numpy and R's defaults.
918pub fn quantile<T: Scalar>(
919    axis: Axis,
920    n_rows: usize,
921    n_cols: usize,
922    x: &[T],
923    q: T,
924    quantile_out: &mut [T],
925    qtype: QuantileType,
926) -> Result<()> {
927    T::quantile(
928        Layout::RowMajor,
929        axis,
930        n_rows,
931        n_cols,
932        x,
933        n_cols,
934        q,
935        quantile_out,
936        qtype,
937    )
938}
939
940/// Compute Tukey's five-number summary (min, lower hinge, median,
941/// upper hinge, max) along `axis`.
942pub fn five_point_summary<T: Scalar>(
943    axis: Axis,
944    n_rows: usize,
945    n_cols: usize,
946    x: &[T],
947    min: &mut [T],
948    lower: &mut [T],
949    median: &mut [T],
950    upper: &mut [T],
951    max: &mut [T],
952) -> Result<()> {
953    T::five_point_summary(
954        Layout::RowMajor,
955        axis,
956        n_rows,
957        n_cols,
958        x,
959        n_cols,
960        min,
961        lower,
962        median,
963        upper,
964        max,
965    )
966}
967
968/// Compute the `n_cols × n_cols` covariance matrix (rows are observations).
969/// `dof` follows the same convention as [`variance`].
970pub fn covariance_matrix<T: Scalar>(
971    n_rows: usize,
972    n_cols: usize,
973    x: &[T],
974    dof: i64,
975    cov: &mut [T],
976) -> Result<()> {
977    T::covariance_matrix(
978        Layout::RowMajor,
979        n_rows,
980        n_cols,
981        x,
982        n_cols,
983        dof,
984        cov,
985        n_cols,
986    )
987}
988
989/// Compute the `n_cols × n_cols` correlation matrix (rows are observations).
990pub fn correlation_matrix<T: Scalar>(
991    n_rows: usize,
992    n_cols: usize,
993    x: &[T],
994    corr: &mut [T],
995) -> Result<()> {
996    T::correlation_matrix(Layout::RowMajor, n_rows, n_cols, x, n_cols, corr, n_cols)
997}
998
999// =========================================================================
1000//   Nonlinear least-squares (NLLS)
1001// =========================================================================
1002
1003/// Type-erased residual closure: maps coefficients `x` of length `n_coef`
1004/// to residuals `res` of length `n_res`. Return `0` on success or non-zero
1005/// to signal an evaluation failure (the solver will return an error).
1006pub type ResFn<'a> = Box<dyn FnMut(&[f64], &mut [f64]) -> i32 + 'a>;
1007
1008/// Type-erased Jacobian closure: writes the `n_res × n_coef` Jacobian
1009/// of the residuals at `x` into `jac`. Layout matches the AOCL
1010/// `"storage scheme"` option (defaults to row-major). Return `0` on
1011/// success.
1012pub type JacFn<'a> = Box<dyn FnMut(&[f64], &mut [f64]) -> i32 + 'a>;
1013
1014struct NllsCallbacks<'a> {
1015    resfun: ResFn<'a>,
1016    resgrd: Option<JacFn<'a>>,
1017    n_coef: usize,
1018    n_res: usize,
1019}
1020
1021unsafe extern "C" fn nlls_resfun_shim(
1022    _n_coef: sys::da_int,
1023    _n_res: sys::da_int,
1024    data: *mut std::os::raw::c_void,
1025    x: *const f64,
1026    res: *mut f64,
1027) -> sys::da_int {
1028    let cbs = unsafe { &mut *(data as *mut NllsCallbacks) };
1029    let x_slice = unsafe { std::slice::from_raw_parts(x, cbs.n_coef) };
1030    let res_slice = unsafe { std::slice::from_raw_parts_mut(res, cbs.n_res) };
1031    // Catch panics so we don't unwind across the FFI boundary.
1032    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1033        (cbs.resfun)(x_slice, res_slice)
1034    }));
1035    match result {
1036        Ok(rc) => rc as sys::da_int,
1037        Err(_) => 1, // signal failure to the solver
1038    }
1039}
1040
1041unsafe extern "C" fn nlls_resgrd_shim(
1042    _n_coef: sys::da_int,
1043    _n_res: sys::da_int,
1044    data: *mut std::os::raw::c_void,
1045    x: *const f64,
1046    jac: *mut f64,
1047) -> sys::da_int {
1048    let cbs = unsafe { &mut *(data as *mut NllsCallbacks) };
1049    let x_slice = unsafe { std::slice::from_raw_parts(x, cbs.n_coef) };
1050    let jac_slice = unsafe { std::slice::from_raw_parts_mut(jac, cbs.n_res * cbs.n_coef) };
1051    let f = match cbs.resgrd.as_mut() {
1052        Some(f) => f,
1053        None => return 1,
1054    };
1055    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(x_slice, jac_slice)));
1056    match result {
1057        Ok(rc) => rc as sys::da_int,
1058        Err(_) => 1,
1059    }
1060}
1061
1062/// Process-wide lock around every call into the NLLS (RALFit) library code: it is not thread-safe.
1063static NLLS_LIB_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
1064
1065fn nlls_lib_lock() -> std::sync::MutexGuard<'static, ()> {
1066    NLLS_LIB_LOCK.lock().unwrap_or_else(|e| e.into_inner())
1067}
1068
1069/// Nonlinear least-squares solver wrapping AOCL's `RAlfit` family.
1070///
1071/// Provide a residual function (mandatory) and optionally a Jacobian.
1072/// If the Jacobian is omitted, AOCL will estimate derivatives by finite
1073/// differences. After [`Nlls::fit`], the optimised coefficients are in
1074/// the user's input vector and a 100-element `rinfo` of solver stats
1075/// can be retrieved via [`Nlls::info`].
1076pub struct Nlls<'a> {
1077    handle: Handle,
1078    callbacks: Box<NllsCallbacks<'a>>,
1079}
1080
1081impl<'a> Nlls<'a> {
1082    /// Build a new NLLS solver with `n_coef` coefficients and `n_res`
1083    /// residuals. `resfun` evaluates `r(x)`; finite differences will
1084    /// estimate the Jacobian unless one is supplied via
1085    /// [`Nlls::with_jacobian`].
1086    pub fn new<F>(n_coef: usize, n_res: usize, resfun: F) -> Result<Self>
1087    where
1088        F: FnMut(&[f64], &mut [f64]) -> i32 + 'a,
1089    {
1090        let _guard = nlls_lib_lock();
1091        let handle = Handle::new_double(HandleKind::Nlls)?;
1092        let callbacks = Box::new(NllsCallbacks {
1093            resfun: Box::new(resfun),
1094            resgrd: None,
1095            n_coef,
1096            n_res,
1097        });
1098        let mut this = Self { handle, callbacks };
1099        this.install()?;
1100        Ok(this)
1101    }
1102
1103    /// Attach an analytic Jacobian. Layout follows the `"storage scheme"`
1104    /// option set on the underlying handle (default row-major).
1105    pub fn with_jacobian<G>(mut self, resgrd: G) -> Result<Self>
1106    where
1107        G: FnMut(&[f64], &mut [f64]) -> i32 + 'a,
1108    {
1109        self.callbacks.resgrd = Some(Box::new(resgrd));
1110        self.install()?;
1111        Ok(self)
1112    }
1113
1114    fn install(&mut self) -> Result<()> {
1115        let resgrd = if self.callbacks.resgrd.is_some() {
1116            Some(nlls_resgrd_shim as unsafe extern "C" fn(_, _, _, _, _) -> _)
1117        } else {
1118            None
1119        };
1120        let status = unsafe {
1121            sys::da_nlls_define_residuals_d(
1122                self.handle.raw,
1123                self.callbacks.n_coef as sys::da_int,
1124                self.callbacks.n_res as sys::da_int,
1125                Some(nlls_resfun_shim),
1126                resgrd,
1127                None,
1128                None,
1129            )
1130        };
1131        if status != sys::da_status__da_status_success {
1132            self.handle.note_status(status);
1133            let extra = self.handle.last_error_message().unwrap_or_default();
1134            return Err(Error::Status {
1135                component: "data-analytics",
1136                code: status as i64,
1137                message: format!("nlls define_residuals failed: {extra}"),
1138            });
1139        }
1140        Ok(())
1141    }
1142
1143    /// Borrow the underlying handle to set NLLS-specific options
1144    /// (`"ralfit iteration limit"`, `"storage scheme"`, etc.).
1145    pub fn handle_mut(&mut self) -> &mut Handle {
1146        &mut self.handle
1147    }
1148
1149    /// Constrain coefficients to lie within `lower[i] <= x[i] <= upper[i]`.
1150    /// Pass `None` for an unbounded side; the slices must have length
1151    /// `n_coef`.
1152    pub fn set_bounds(
1153        &mut self,
1154        lower: Option<&mut [f64]>,
1155        upper: Option<&mut [f64]>,
1156    ) -> Result<()> {
1157        let n_coef = self.callbacks.n_coef as sys::da_int;
1158        let l_ptr = lower
1159            .as_ref()
1160            .map_or(std::ptr::null_mut(), |s| s.as_ptr() as *mut f64);
1161        let u_ptr = upper
1162            .as_ref()
1163            .map_or(std::ptr::null_mut(), |s| s.as_ptr() as *mut f64);
1164        if let Some(l) = lower.as_ref() {
1165            if l.len() < self.callbacks.n_coef {
1166                return Err(Error::InvalidArgument(format!(
1167                    "set_bounds: lower length {} < n_coef = {}",
1168                    l.len(),
1169                    self.callbacks.n_coef
1170                )));
1171            }
1172        }
1173        if let Some(u) = upper.as_ref() {
1174            if u.len() < self.callbacks.n_coef {
1175                return Err(Error::InvalidArgument(format!(
1176                    "set_bounds: upper length {} < n_coef = {}",
1177                    u.len(),
1178                    self.callbacks.n_coef
1179                )));
1180            }
1181        }
1182        let _guard = nlls_lib_lock();
1183        let status = unsafe { sys::da_nlls_define_bounds_d(self.handle.raw, n_coef, l_ptr, u_ptr) };
1184        check_status("data-analytics", status)
1185    }
1186
1187    /// Set per-residual weights `w_i = √W_ii` (length `n_res`).
1188    pub fn set_weights(&mut self, weights: &mut [f64]) -> Result<()> {
1189        if weights.len() < self.callbacks.n_res {
1190            return Err(Error::InvalidArgument(format!(
1191                "set_weights: weights length {} < n_res = {}",
1192                weights.len(),
1193                self.callbacks.n_res
1194            )));
1195        }
1196        let _guard = nlls_lib_lock();
1197        let status = unsafe {
1198            sys::da_nlls_define_weights_d(
1199                self.handle.raw,
1200                self.callbacks.n_res as sys::da_int,
1201                weights.as_mut_ptr(),
1202            )
1203        };
1204        check_status("data-analytics", status)
1205    }
1206
1207    /// Run the optimiser. On entry `coef` is the initial guess; on
1208    /// success it holds the optimised coefficients.
1209    ///
1210    /// Concurrent solves are serialised: RALFit in `aocl-da.dll` is not thread-safe (AOCL 6.0.68, Windows: concurrent
1211    /// solves from several threads crashed the process), so `Nlls::new` (which defines the residuals), `set_bounds`,
1212    /// `set_weights`, `fit` and `info` take one process-wide lock. Two `Nlls` fits on different threads therefore run one
1213    /// after the other. Option setting through [`Nlls::handle_mut`] is NOT covered by the lock.
1214    pub fn fit(&mut self, coef: &mut [f64]) -> Result<()> {
1215        let _guard = nlls_lib_lock();
1216        if coef.len() < self.callbacks.n_coef {
1217            return Err(Error::InvalidArgument(format!(
1218                "nlls fit: coef length {} < n_coef = {}",
1219                coef.len(),
1220                self.callbacks.n_coef
1221            )));
1222        }
1223        let udata = self.callbacks.as_mut() as *mut NllsCallbacks as *mut std::os::raw::c_void;
1224        let status = unsafe {
1225            sys::da_nlls_fit_d(
1226                self.handle.raw,
1227                self.callbacks.n_coef as sys::da_int,
1228                coef.as_mut_ptr(),
1229                udata,
1230            )
1231        };
1232        if status != sys::da_status__da_status_success {
1233            self.handle.note_status(status);
1234            let extra = self.handle.last_error_message().unwrap_or_default();
1235            return Err(Error::Status {
1236                component: "data-analytics",
1237                code: status as i64,
1238                message: format!("nlls fit failed: {extra}"),
1239            });
1240        }
1241        Ok(())
1242    }
1243
1244    /// Retrieve the solver's information vector (`rinfo`, length 100) —
1245    /// see AOCL's documentation for the index meanings:
1246    /// `info_objective` (0), `info_grad_norm` (1), `info_iter` (2),
1247    /// `info_time` (3), etc.
1248    pub fn info(&self) -> Result<Vec<f64>> {
1249        let _guard = nlls_lib_lock();
1250        // rinfo is a fixed-size 100-element vector for NLLS.
1251        let mut dim: sys::da_int = 100;
1252        let mut out = vec![0.0_f64; 100];
1253        let status = unsafe {
1254            sys::da_handle_get_result_d(
1255                self.handle.raw,
1256                sys::da_result__da_rinfo,
1257                &mut dim,
1258                out.as_mut_ptr(),
1259            )
1260        };
1261        if status != sys::da_status__da_status_success {
1262            self.handle.note_status(status);
1263            let extra = self.handle.last_error_message().unwrap_or_default();
1264            return Err(Error::Status {
1265                component: "data-analytics",
1266                code: status as i64,
1267                message: format!("nlls info: {extra}"),
1268            });
1269        }
1270        out.truncate(dim as usize);
1271        Ok(out)
1272    }
1273}
1274
1275impl<'a> std::fmt::Debug for Nlls<'a> {
1276    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1277        f.debug_struct("Nlls")
1278            .field("n_coef", &self.callbacks.n_coef)
1279            .field("n_res", &self.callbacks.n_res)
1280            .field("handle", &self.handle)
1281            .finish()
1282    }
1283}
1284
1285// =========================================================================
1286//   Datastore (CSV loading + column selection)
1287// =========================================================================
1288
1289/// RAII wrapper around `da_datastore` — AOCL-DA's container for tabular
1290/// data loaded from CSV. Use it to read a file, query its dimensions,
1291/// label or select columns by name, and extract numeric blocks into
1292/// caller-provided buffers.
1293pub struct Datastore {
1294    raw: sys::da_datastore,
1295}
1296
1297unsafe impl Send for Datastore {}
1298
1299impl Datastore {
1300    /// Create a fresh empty datastore.
1301    pub fn new() -> Result<Self> {
1302        let mut raw: sys::da_datastore = std::ptr::null_mut();
1303        let status = unsafe { sys::da_datastore_init(&mut raw) };
1304        check_status("data-analytics", status)?;
1305        if raw.is_null() {
1306            return Err(Error::AllocationFailed("data-analytics"));
1307        }
1308        Ok(Self { raw })
1309    }
1310
1311    /// Set an integer-valued datastore option (e.g.
1312    /// `set_int_option("use header row", 1)`,
1313    /// `set_int_option("whitespace delimiter", 1)`).
1314    pub fn set_int_option(&mut self, name: &str, value: i64) -> Result<()> {
1315        let cs = std::ffi::CString::new(name)
1316            .map_err(|e| Error::InvalidArgument(format!("set_int_option: {e}")))?;
1317        let status = unsafe {
1318            sys::da_datastore_options_set_int(self.raw, cs.as_ptr(), value as sys::da_int)
1319        };
1320        check_status("data-analytics", status)
1321    }
1322
1323    /// Set a string-valued datastore option (e.g. `"comment"` to set a
1324    /// comment-line prefix character, `"storage order"` to choose
1325    /// row-major vs column-major).
1326    pub fn set_string_option(&mut self, name: &str, value: &str) -> Result<()> {
1327        let n = std::ffi::CString::new(name)
1328            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
1329        let v = std::ffi::CString::new(value)
1330            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
1331        let status =
1332            unsafe { sys::da_datastore_options_set_string(self.raw, n.as_ptr(), v.as_ptr()) };
1333        check_status("data-analytics", status)
1334    }
1335
1336    /// Load a CSV file into the datastore.
1337    pub fn load_csv(&mut self, path: &str) -> Result<()> {
1338        let cs = std::ffi::CString::new(path)
1339            .map_err(|e| Error::InvalidArgument(format!("load_csv: {e}")))?;
1340        let status = unsafe { sys::da_data_load_from_csv(self.raw, cs.as_ptr()) };
1341        check_status("data-analytics", status)
1342    }
1343
1344    /// Number of rows currently held by the store.
1345    pub fn n_rows(&self) -> Result<usize> {
1346        let mut n: sys::da_int = 0;
1347        let status = unsafe { sys::da_data_get_n_rows(self.raw, &mut n) };
1348        check_status("data-analytics", status)?;
1349        Ok(n as usize)
1350    }
1351
1352    /// Number of columns currently held by the store.
1353    pub fn n_cols(&self) -> Result<usize> {
1354        let mut n: sys::da_int = 0;
1355        let status = unsafe { sys::da_data_get_n_cols(self.raw, &mut n) };
1356        check_status("data-analytics", status)?;
1357        Ok(n as usize)
1358    }
1359
1360    /// `(n_rows, n_cols)` dimensions.
1361    pub fn dims(&self) -> Result<(usize, usize)> {
1362        Ok((self.n_rows()?, self.n_cols()?))
1363    }
1364
1365    /// Select a contiguous range of columns into the named selection
1366    /// `key` (zero-based, inclusive bounds). Use [`Datastore::extract_f64`]
1367    /// to read the selected columns into a buffer.
1368    pub fn select_columns(&mut self, key: &str, lbound: usize, ubound: usize) -> Result<()> {
1369        let cs = std::ffi::CString::new(key)
1370            .map_err(|e| Error::InvalidArgument(format!("select_columns: {e}")))?;
1371        let status = unsafe {
1372            sys::da_data_select_columns(
1373                self.raw,
1374                cs.as_ptr(),
1375                lbound as sys::da_int,
1376                ubound as sys::da_int,
1377            )
1378        };
1379        check_status("data-analytics", status)
1380    }
1381
1382    /// Select a contiguous range of rows into the named selection `key`.
1383    pub fn select_rows(&mut self, key: &str, lbound: usize, ubound: usize) -> Result<()> {
1384        let cs = std::ffi::CString::new(key)
1385            .map_err(|e| Error::InvalidArgument(format!("select_rows: {e}")))?;
1386        let status = unsafe {
1387            sys::da_data_select_rows(
1388                self.raw,
1389                cs.as_ptr(),
1390                lbound as sys::da_int,
1391                ubound as sys::da_int,
1392            )
1393        };
1394        check_status("data-analytics", status)
1395    }
1396
1397    /// Extract the named selection into `data` as `f64` values, in the
1398    /// order specified by `layout`. `lddata` is the leading dimension
1399    /// of the output buffer.
1400    pub fn extract_f64(
1401        &self,
1402        key: &str,
1403        layout: Layout,
1404        data: &mut [f64],
1405        lddata: usize,
1406    ) -> Result<()> {
1407        let cs = std::ffi::CString::new(key)
1408            .map_err(|e| Error::InvalidArgument(format!("extract_f64: {e}")))?;
1409        let status = unsafe {
1410            sys::da_data_extract_selection_real_d(
1411                self.raw,
1412                cs.as_ptr(),
1413                layout_raw(layout),
1414                data.as_mut_ptr(),
1415                lddata as sys::da_int,
1416            )
1417        };
1418        check_status("data-analytics", status)
1419    }
1420
1421    /// Borrow the raw `da_datastore` handle (for routines this crate
1422    /// doesn't yet wrap).
1423    pub fn as_raw(&self) -> sys::da_datastore {
1424        self.raw
1425    }
1426}
1427
1428impl Drop for Datastore {
1429    fn drop(&mut self) {
1430        if !self.raw.is_null() {
1431            unsafe { sys::da_datastore_destroy(&mut self.raw) };
1432            self.raw = std::ptr::null_mut();
1433        }
1434    }
1435}
1436
1437impl std::fmt::Debug for Datastore {
1438    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1439        f.debug_struct("Datastore").finish_non_exhaustive()
1440    }
1441}
1442
1443// =========================================================================
1444//   Pairwise distances
1445// =========================================================================
1446
1447/// Distance metric for [`pairwise_distances`].
1448#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1449#[non_exhaustive]
1450pub enum Metric {
1451    /// Euclidean distance (`L2`).
1452    Euclidean,
1453    /// Squared Euclidean distance (`Σ (xᵢ-yᵢ)²` without the square root).
1454    SqEuclidean,
1455    /// Minkowski distance with parameter `p` (defaults to L2 at p=2).
1456    Minkowski,
1457    /// Manhattan / `L1` / cityblock distance.
1458    Manhattan,
1459    /// Cosine distance: `1 - cos(angle)`.
1460    Cosine,
1461}
1462
1463impl Metric {
1464    fn raw(self) -> sys::da_metric {
1465        match self {
1466            Metric::Euclidean => sys::da_metric__da_euclidean,
1467            Metric::SqEuclidean => sys::da_metric__da_sqeuclidean,
1468            Metric::Minkowski => sys::da_metric__da_minkowski,
1469            Metric::Manhattan => sys::da_metric__da_manhattan,
1470            Metric::Cosine => sys::da_metric__da_cosine,
1471        }
1472    }
1473}
1474
1475/// Scalar element type usable with [`pairwise_distances`].
1476pub trait DistScalar: Scalar {
1477    /// Compute the pairwise distance matrix `D[i,j] = metric(X[i], Y[j])`.
1478    /// If `y` is `None`, distances are computed within `x` (so `D` is
1479    /// `m × m`); otherwise `D` is `m × n`.
1480    fn pairwise_distances(
1481        layout: Layout,
1482        m: usize,
1483        n: usize,
1484        k: usize,
1485        x: &[Self],
1486        ldx: usize,
1487        y: Option<&[Self]>,
1488        ldy: usize,
1489        d: &mut [Self],
1490        ldd: usize,
1491        p: Self,
1492        metric: Metric,
1493    ) -> Result<()>;
1494}
1495
1496macro_rules! impl_dist_scalar {
1497    ($t:ty, $fn:ident) => {
1498        impl DistScalar for $t {
1499            fn pairwise_distances(
1500                layout: Layout,
1501                m: usize,
1502                n: usize,
1503                k: usize,
1504                x: &[Self],
1505                ldx: usize,
1506                y: Option<&[Self]>,
1507                ldy: usize,
1508                d: &mut [Self],
1509                ldd: usize,
1510                p: Self,
1511                metric: Metric,
1512            ) -> Result<()> {
1513                check_dense("pairwise_distances", "x", layout, m, k, ldx, x.len())?;
1514                if let Some(yv) = y {
1515                    check_dense("pairwise_distances", "y", layout, n, k, ldy, yv.len())?;
1516                }
1517                let d_cols = if y.is_some() { n } else { m };
1518                check_dense("pairwise_distances", "d", layout, m, d_cols, ldd, d.len())?;
1519                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1520                let status = unsafe {
1521                    sys::$fn(
1522                        layout_raw(layout),
1523                        m as sys::da_int,
1524                        n as sys::da_int,
1525                        k as sys::da_int,
1526                        x.as_ptr(),
1527                        ldx as sys::da_int,
1528                        y_ptr,
1529                        ldy as sys::da_int,
1530                        d.as_mut_ptr(),
1531                        ldd as sys::da_int,
1532                        p,
1533                        metric.raw(),
1534                    )
1535                };
1536                check_status("data-analytics", status)
1537            }
1538        }
1539    };
1540}
1541
1542impl_dist_scalar!(f32, da_pairwise_distances_s);
1543impl_dist_scalar!(f64, da_pairwise_distances_d);
1544
1545// =========================================================================
1546//   Kernel functions (linear / RBF / polynomial / sigmoid)
1547// =========================================================================
1548
1549/// Scalar element type for kernel-matrix computations.
1550pub trait KernelScalar: Scalar {
1551    /// Linear kernel: `K(x, y) = x · y`.
1552    fn linear_kernel(
1553        layout: Layout,
1554        m: usize,
1555        n: usize,
1556        k: usize,
1557        x: &[Self],
1558        ldx: usize,
1559        y: Option<&[Self]>,
1560        ldy: usize,
1561        d: &mut [Self],
1562        ldd: usize,
1563    ) -> Result<()>;
1564
1565    /// RBF (Gaussian) kernel: `K(x, y) = exp(-γ · ‖x − y‖²)`.
1566    fn rbf_kernel(
1567        layout: Layout,
1568        m: usize,
1569        n: usize,
1570        k: usize,
1571        x: &[Self],
1572        ldx: usize,
1573        y: Option<&[Self]>,
1574        ldy: usize,
1575        d: &mut [Self],
1576        ldd: usize,
1577        gamma: Self,
1578    ) -> Result<()>;
1579
1580    /// Polynomial kernel: `K(x, y) = (γ · x · y + c)^degree`.
1581    fn polynomial_kernel(
1582        layout: Layout,
1583        m: usize,
1584        n: usize,
1585        k: usize,
1586        x: &[Self],
1587        ldx: usize,
1588        y: Option<&[Self]>,
1589        ldy: usize,
1590        d: &mut [Self],
1591        ldd: usize,
1592        gamma: Self,
1593        degree: i64,
1594        coef0: Self,
1595    ) -> Result<()>;
1596
1597    /// Sigmoid kernel: `K(x, y) = tanh(γ · x · y + c)`.
1598    fn sigmoid_kernel(
1599        layout: Layout,
1600        m: usize,
1601        n: usize,
1602        k: usize,
1603        x: &[Self],
1604        ldx: usize,
1605        y: Option<&[Self]>,
1606        ldy: usize,
1607        d: &mut [Self],
1608        ldd: usize,
1609        gamma: Self,
1610        coef0: Self,
1611    ) -> Result<()>;
1612}
1613
1614macro_rules! impl_kernel_scalar {
1615    ($t:ty, $linear:ident, $rbf:ident, $poly:ident, $sigmoid:ident) => {
1616        impl KernelScalar for $t {
1617            fn linear_kernel(
1618                layout: Layout,
1619                m: usize,
1620                n: usize,
1621                k: usize,
1622                x: &[Self],
1623                ldx: usize,
1624                y: Option<&[Self]>,
1625                ldy: usize,
1626                d: &mut [Self],
1627                ldd: usize,
1628            ) -> Result<()> {
1629                check_dense("linear_kernel", "x", layout, m, k, ldx, x.len())?;
1630                if let Some(yv) = y {
1631                    check_dense("linear_kernel", "y", layout, n, k, ldy, yv.len())?;
1632                }
1633                let d_cols = if y.is_some() { n } else { m };
1634                check_dense("linear_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1635                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1636                let status = unsafe {
1637                    sys::$linear(
1638                        layout_raw(layout),
1639                        m as sys::da_int,
1640                        n as sys::da_int,
1641                        k as sys::da_int,
1642                        x.as_ptr(),
1643                        ldx as sys::da_int,
1644                        y_ptr,
1645                        ldy as sys::da_int,
1646                        d.as_mut_ptr(),
1647                        ldd as sys::da_int,
1648                    )
1649                };
1650                check_status("data-analytics", status)
1651            }
1652
1653            fn rbf_kernel(
1654                layout: Layout,
1655                m: usize,
1656                n: usize,
1657                k: usize,
1658                x: &[Self],
1659                ldx: usize,
1660                y: Option<&[Self]>,
1661                ldy: usize,
1662                d: &mut [Self],
1663                ldd: usize,
1664                gamma: Self,
1665            ) -> Result<()> {
1666                check_dense("rbf_kernel", "x", layout, m, k, ldx, x.len())?;
1667                if let Some(yv) = y {
1668                    check_dense("rbf_kernel", "y", layout, n, k, ldy, yv.len())?;
1669                }
1670                let d_cols = if y.is_some() { n } else { m };
1671                check_dense("rbf_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1672                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1673                let status = unsafe {
1674                    sys::$rbf(
1675                        layout_raw(layout),
1676                        m as sys::da_int,
1677                        n as sys::da_int,
1678                        k as sys::da_int,
1679                        x.as_ptr(),
1680                        ldx as sys::da_int,
1681                        y_ptr,
1682                        ldy as sys::da_int,
1683                        d.as_mut_ptr(),
1684                        ldd as sys::da_int,
1685                        gamma,
1686                    )
1687                };
1688                check_status("data-analytics", status)
1689            }
1690
1691            fn polynomial_kernel(
1692                layout: Layout,
1693                m: usize,
1694                n: usize,
1695                k: usize,
1696                x: &[Self],
1697                ldx: usize,
1698                y: Option<&[Self]>,
1699                ldy: usize,
1700                d: &mut [Self],
1701                ldd: usize,
1702                gamma: Self,
1703                degree: i64,
1704                coef0: Self,
1705            ) -> Result<()> {
1706                check_dense("polynomial_kernel", "x", layout, m, k, ldx, x.len())?;
1707                if let Some(yv) = y {
1708                    check_dense("polynomial_kernel", "y", layout, n, k, ldy, yv.len())?;
1709                }
1710                let d_cols = if y.is_some() { n } else { m };
1711                check_dense("polynomial_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1712                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1713                let status = unsafe {
1714                    sys::$poly(
1715                        layout_raw(layout),
1716                        m as sys::da_int,
1717                        n as sys::da_int,
1718                        k as sys::da_int,
1719                        x.as_ptr(),
1720                        ldx as sys::da_int,
1721                        y_ptr,
1722                        ldy as sys::da_int,
1723                        d.as_mut_ptr(),
1724                        ldd as sys::da_int,
1725                        gamma,
1726                        degree as sys::da_int,
1727                        coef0,
1728                    )
1729                };
1730                check_status("data-analytics", status)
1731            }
1732
1733            fn sigmoid_kernel(
1734                layout: Layout,
1735                m: usize,
1736                n: usize,
1737                k: usize,
1738                x: &[Self],
1739                ldx: usize,
1740                y: Option<&[Self]>,
1741                ldy: usize,
1742                d: &mut [Self],
1743                ldd: usize,
1744                gamma: Self,
1745                coef0: Self,
1746            ) -> Result<()> {
1747                check_dense("sigmoid_kernel", "x", layout, m, k, ldx, x.len())?;
1748                if let Some(yv) = y {
1749                    check_dense("sigmoid_kernel", "y", layout, n, k, ldy, yv.len())?;
1750                }
1751                let d_cols = if y.is_some() { n } else { m };
1752                check_dense("sigmoid_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1753                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1754                let status = unsafe {
1755                    sys::$sigmoid(
1756                        layout_raw(layout),
1757                        m as sys::da_int,
1758                        n as sys::da_int,
1759                        k as sys::da_int,
1760                        x.as_ptr(),
1761                        ldx as sys::da_int,
1762                        y_ptr,
1763                        ldy as sys::da_int,
1764                        d.as_mut_ptr(),
1765                        ldd as sys::da_int,
1766                        gamma,
1767                        coef0,
1768                    )
1769                };
1770                check_status("data-analytics", status)
1771            }
1772        }
1773    };
1774}
1775
1776impl_kernel_scalar!(
1777    f32,
1778    da_linear_kernel_s,
1779    da_rbf_kernel_s,
1780    da_polynomial_kernel_s,
1781    da_sigmoid_kernel_s
1782);
1783impl_kernel_scalar!(
1784    f64,
1785    da_linear_kernel_d,
1786    da_rbf_kernel_d,
1787    da_polynomial_kernel_d,
1788    da_sigmoid_kernel_d
1789);
1790
1791/// Linear kernel `K(x, y) = x · y` between rows of row-major matrices
1792/// `x` (`m × k`) and optionally `y` (`n × k`). Output `d` is `m × n`
1793/// (or `m × m` if `y` is `None`).
1794pub fn linear_kernel<T: KernelScalar>(
1795    m: usize,
1796    n: usize,
1797    k: usize,
1798    x: &[T],
1799    y: Option<&[T]>,
1800    d: &mut [T],
1801) -> Result<()> {
1802    let ldd = if y.is_none() { m } else { n };
1803    T::linear_kernel(Layout::RowMajor, m, n, k, x, k, y, k, d, ldd)
1804}
1805
1806/// RBF kernel `K(x, y) = exp(-γ · ‖x − y‖²)` (row-major).
1807pub fn rbf_kernel<T: KernelScalar>(
1808    m: usize,
1809    n: usize,
1810    k: usize,
1811    x: &[T],
1812    y: Option<&[T]>,
1813    d: &mut [T],
1814    gamma: T,
1815) -> Result<()> {
1816    let ldd = if y.is_none() { m } else { n };
1817    T::rbf_kernel(Layout::RowMajor, m, n, k, x, k, y, k, d, ldd, gamma)
1818}
1819
1820/// Polynomial kernel `K(x, y) = (γ · x · y + c)^degree` (row-major).
1821pub fn polynomial_kernel<T: KernelScalar>(
1822    m: usize,
1823    n: usize,
1824    k: usize,
1825    x: &[T],
1826    y: Option<&[T]>,
1827    d: &mut [T],
1828    gamma: T,
1829    degree: i64,
1830    coef0: T,
1831) -> Result<()> {
1832    let ldd = if y.is_none() { m } else { n };
1833    T::polynomial_kernel(
1834        Layout::RowMajor,
1835        m,
1836        n,
1837        k,
1838        x,
1839        k,
1840        y,
1841        k,
1842        d,
1843        ldd,
1844        gamma,
1845        degree,
1846        coef0,
1847    )
1848}
1849
1850/// Sigmoid kernel `K(x, y) = tanh(γ · x · y + c)` (row-major).
1851pub fn sigmoid_kernel<T: KernelScalar>(
1852    m: usize,
1853    n: usize,
1854    k: usize,
1855    x: &[T],
1856    y: Option<&[T]>,
1857    d: &mut [T],
1858    gamma: T,
1859    coef0: T,
1860) -> Result<()> {
1861    let ldd = if y.is_none() { m } else { n };
1862    T::sigmoid_kernel(Layout::RowMajor, m, n, k, x, k, y, k, d, ldd, gamma, coef0)
1863}
1864
1865/// Compute the pairwise distance matrix between rows of `x` (and
1866/// optionally rows of `y`) under the given `metric`.
1867///
1868/// `x` is `m × k` row-major; `y` (optional) is `n × k` row-major. When
1869/// `y` is `None`, distances are computed *within* `x` and the output
1870/// `d` is `m × m`. Otherwise `d` is `m × n`. `p` is the Minkowski
1871/// exponent (ignored for non-Minkowski metrics).
1872pub fn pairwise_distances<T: DistScalar>(
1873    m: usize,
1874    n: usize,
1875    k: usize,
1876    x: &[T],
1877    y: Option<&[T]>,
1878    d: &mut [T],
1879    p: T,
1880    metric: Metric,
1881) -> Result<()> {
1882    let ldd = if y.is_none() { m } else { n };
1883    let ldy = k; // row-major: ldy = k regardless of y being None
1884    T::pairwise_distances(Layout::RowMajor, m, n, k, x, k, y, ldy, d, ldd, p, metric)
1885}
1886
1887// =========================================================================
1888//   da_handle + k-means safe wrapper
1889// =========================================================================
1890
1891/// Type of analytics handle. AOCL-DA uses an opaque handle to track the
1892/// state of an algorithm (data, options, fitted model, predictions).
1893#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1894#[non_exhaustive]
1895pub enum HandleKind {
1896    Linmod,
1897    Pca,
1898    Kmeans,
1899    Dbscan,
1900    DecisionTree,
1901    DecisionForest,
1902    Knn,
1903    Svm,
1904    Nlls,
1905}
1906
1907impl HandleKind {
1908    fn raw(self) -> sys::da_handle_type {
1909        match self {
1910            HandleKind::Linmod => sys::da_handle_type__da_handle_linmod,
1911            HandleKind::Pca => sys::da_handle_type__da_handle_pca,
1912            HandleKind::Kmeans => sys::da_handle_type__da_handle_kmeans,
1913            HandleKind::Dbscan => sys::da_handle_type__da_handle_dbscan,
1914            HandleKind::DecisionTree => sys::da_handle_type__da_handle_decision_tree,
1915            HandleKind::DecisionForest => sys::da_handle_type__da_handle_decision_forest,
1916            // AOCL 5.3 renamed k-NN to nearest neighbours (`da_handle_nn`, `da_nn_*`).
1917            HandleKind::Knn => sys::da_handle_type__da_handle_nn,
1918            HandleKind::Svm => sys::da_handle_type__da_handle_svm,
1919            HandleKind::Nlls => sys::da_handle_type__da_handle_nlls,
1920        }
1921    }
1922}
1923
1924/// Internal precision selector for [`Handle`]: f64 (`Double`) or
1925/// f32 (`Single`). The choice determines which underlying `da_*_d` /
1926/// `da_*_s` C entry points are used.
1927#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1928pub enum Precision {
1929    Single,
1930    Double,
1931}
1932
1933/// RAII wrapper around `da_handle`. Tracks the algorithm and precision
1934/// chosen at construction time.
1935pub struct Handle {
1936    raw: sys::da_handle,
1937    kind: HandleKind,
1938    precision: Precision,
1939    /// A call on this handle has failed, so the library has a message stored. AOCL 6.0.68's `da_handle_get_error_message`
1940    /// on a handle with NO stored error can return success with a pointer to uninitialised heap (not a valid C string),
1941    /// so the message is only read after a failure this wrapper has seen.
1942    error_pending: std::cell::Cell<bool>,
1943}
1944
1945unsafe impl Send for Handle {}
1946
1947impl Handle {
1948    /// Create an `f64` handle for the given algorithm.
1949    pub fn new_double(kind: HandleKind) -> Result<Self> {
1950        let mut raw: sys::da_handle = std::ptr::null_mut();
1951        let status = unsafe { sys::da_handle_init_d(&mut raw, kind.raw()) };
1952        check_status("data-analytics", status)?;
1953        if raw.is_null() {
1954            return Err(Error::AllocationFailed("data-analytics"));
1955        }
1956        Ok(Self {
1957            raw,
1958            kind,
1959            precision: Precision::Double,
1960            error_pending: std::cell::Cell::new(false),
1961        })
1962    }
1963
1964    /// Create an `f32` handle.
1965    pub fn new_single(kind: HandleKind) -> Result<Self> {
1966        let mut raw: sys::da_handle = std::ptr::null_mut();
1967        let status = unsafe { sys::da_handle_init_s(&mut raw, kind.raw()) };
1968        check_status("data-analytics", status)?;
1969        if raw.is_null() {
1970            return Err(Error::AllocationFailed("data-analytics"));
1971        }
1972        Ok(Self {
1973            raw,
1974            kind,
1975            precision: Precision::Single,
1976            error_pending: std::cell::Cell::new(false),
1977        })
1978    }
1979
1980    /// Set an integer-valued option.
1981    pub fn set_int_option(&mut self, name: &str, value: i64) -> Result<()> {
1982        let cs = std::ffi::CString::new(name)
1983            .map_err(|e| Error::InvalidArgument(format!("set_int_option: {e}")))?;
1984        let status =
1985            unsafe { sys::da_options_set_int(self.raw, cs.as_ptr(), value as sys::da_int) };
1986        self.note_status(status);
1987        check_status("data-analytics", status)
1988    }
1989
1990    /// Set a string-valued option.
1991    pub fn set_string_option(&mut self, name: &str, value: &str) -> Result<()> {
1992        let n = std::ffi::CString::new(name)
1993            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
1994        let v = std::ffi::CString::new(value)
1995            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
1996        let status = unsafe { sys::da_options_set_string(self.raw, n.as_ptr(), v.as_ptr()) };
1997        self.note_status(status);
1998        check_status("data-analytics", status)
1999    }
2000
2001    /// Borrow the raw handle for routines this crate doesn't yet wrap.
2002    pub fn as_raw(&self) -> sys::da_handle {
2003        self.raw
2004    }
2005
2006    /// Returns `(kind, precision)`.
2007    pub fn info(&self) -> (HandleKind, Precision) {
2008        (self.kind, self.precision)
2009    }
2010
2011    /// Fetch the most recent detailed error message AOCL-DA stored on
2012    /// this handle, or `None` if there isn't one. Useful for diagnosing
2013    /// which option or input value the C library found objectionable.
2014    pub fn last_error_message(&self) -> Option<String> {
2015        if !self.error_pending.get() {
2016            // No failure seen on this handle: the library may hand back uninitialised memory here (see `error_pending`).
2017            return None;
2018        }
2019        let mut p: *mut std::os::raw::c_char = std::ptr::null_mut();
2020        let status = unsafe { sys::da_handle_get_error_message(self.raw, &mut p) };
2021        if status != sys::da_status__da_status_success || p.is_null() {
2022            return None;
2023        }
2024        let s = unsafe { std::ffi::CStr::from_ptr(p) }
2025            .to_string_lossy()
2026            .into_owned();
2027        // The library returns a freshly allocated buffer that the caller
2028        // must free with libc::free; we don't link libc here, so skip the
2029        // free. The leak is bounded (one per query) and not worth pulling
2030        // in libc just to plug.
2031        if s.is_empty() {
2032            None
2033        } else {
2034            Some(s)
2035        }
2036    }
2037
2038    /// Record that a call on this handle returned `status`: a failure means the library has an error message stored.
2039    pub(crate) fn note_status(&self, status: sys::da_status) {
2040        if status != sys::da_status__da_status_success {
2041            self.error_pending.set(true);
2042        }
2043    }
2044}
2045
2046impl Drop for Handle {
2047    fn drop(&mut self) {
2048        if !self.raw.is_null() {
2049            unsafe { sys::da_handle_destroy(&mut self.raw) };
2050            self.raw = std::ptr::null_mut();
2051        }
2052    }
2053}
2054
2055impl std::fmt::Debug for Handle {
2056    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2057        f.debug_struct("Handle")
2058            .field("kind", &self.kind)
2059            .field("precision", &self.precision)
2060            .finish_non_exhaustive()
2061    }
2062}
2063
2064/// k-means clustering wrapper. Holds an [`Handle`] specialised for
2065/// `da_handle_kmeans` and exposes the typical fit/predict interface.
2066pub struct KMeans {
2067    handle: Handle,
2068}
2069
2070impl KMeans {
2071    /// Build a new k-means model with `n_clusters` clusters in `f64`
2072    /// precision.
2073    pub fn new(n_clusters: usize) -> Result<Self> {
2074        let mut handle = Handle::new_double(HandleKind::Kmeans)?;
2075        handle.set_int_option("n_clusters", n_clusters as i64)?;
2076        Ok(Self { handle })
2077    }
2078
2079    /// Fit on `n_samples × n_features` data matrix in **column-major**
2080    /// layout (one column per feature; `lda = n_samples`). This matches
2081    /// AOCL-DA's default storage convention.
2082    pub fn fit(&mut self, n_samples: usize, n_features: usize, data: &[f64]) -> Result<()> {
2083        if data.len() < n_samples * n_features {
2084            return Err(Error::InvalidArgument(format!(
2085                "fit: data length {} < n_samples·n_features = {}",
2086                data.len(),
2087                n_samples * n_features
2088            )));
2089        }
2090        let lda = n_samples;
2091        let status = unsafe {
2092            sys::da_kmeans_set_data_d(
2093                self.handle.raw,
2094                n_samples as sys::da_int,
2095                n_features as sys::da_int,
2096                data.as_ptr(),
2097                lda as sys::da_int,
2098            )
2099        };
2100        check_status("data-analytics", status)?;
2101        let status = unsafe { sys::da_kmeans_compute_d(self.handle.raw) };
2102        check_status("data-analytics", status)
2103    }
2104
2105    /// Predict cluster labels for new samples in column-major layout.
2106    pub fn predict(
2107        &mut self,
2108        k_samples: usize,
2109        k_features: usize,
2110        y: &[f64],
2111        labels: &mut [i32],
2112    ) -> Result<()> {
2113        check_dense(
2114            "kmeans predict",
2115            "y",
2116            Layout::ColMajor,
2117            k_samples,
2118            k_features,
2119            k_samples,
2120            y.len(),
2121        )?;
2122        if labels.len() < k_samples {
2123            return Err(Error::InvalidArgument(format!(
2124                "predict: labels length {} < k_samples = {k_samples}",
2125                labels.len()
2126            )));
2127        }
2128        let mut out = IntsOut::new(k_samples);
2129        let status = unsafe {
2130            sys::da_kmeans_predict_d(
2131                self.handle.raw,
2132                k_samples as sys::da_int,
2133                k_features as sys::da_int,
2134                y.as_ptr(),
2135                k_samples as sys::da_int,
2136                out.as_mut_ptr(),
2137            )
2138        };
2139        check_status("data-analytics", status)?;
2140        out.write_back(labels, k_samples)
2141    }
2142}
2143
2144impl std::fmt::Debug for KMeans {
2145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2146        f.debug_struct("KMeans")
2147            .field("handle", &self.handle)
2148            .finish()
2149    }
2150}
2151
2152/// Principal Component Analysis. Reduces an `n_samples × n_features`
2153/// matrix to a lower-dimensional representation.
2154pub struct Pca {
2155    handle: Handle,
2156}
2157
2158impl Pca {
2159    /// Build a new PCA handle that retains `n_components` principal
2160    /// directions, in `f64` precision.
2161    pub fn new(n_components: usize) -> Result<Self> {
2162        let mut handle = Handle::new_double(HandleKind::Pca)?;
2163        handle.set_int_option("n_components", n_components as i64)?;
2164        Ok(Self { handle })
2165    }
2166
2167    /// Fit on column-major `n_samples × n_features` data.
2168    pub fn fit(&mut self, n_samples: usize, n_features: usize, data: &[f64]) -> Result<()> {
2169        if data.len() < n_samples * n_features {
2170            return Err(Error::InvalidArgument(format!(
2171                "PCA fit: data length {} < n_samples·n_features = {}",
2172                data.len(),
2173                n_samples * n_features
2174            )));
2175        }
2176        let lda = n_samples;
2177        let status = unsafe {
2178            sys::da_pca_set_data_d(
2179                self.handle.raw,
2180                n_samples as sys::da_int,
2181                n_features as sys::da_int,
2182                data.as_ptr(),
2183                lda as sys::da_int,
2184            )
2185        };
2186        check_status("data-analytics", status)?;
2187        let status = unsafe { sys::da_pca_compute_d(self.handle.raw) };
2188        check_status("data-analytics", status)
2189    }
2190
2191    /// Project `m_samples × m_features` new data into the fitted
2192    /// principal-component space. `out` receives the transformed
2193    /// `m_samples × n_components` matrix in column-major layout
2194    /// (`ldx_transform = m_samples`).
2195    pub fn transform(
2196        &mut self,
2197        m_samples: usize,
2198        m_features: usize,
2199        x: &[f64],
2200        n_components: usize,
2201        out: &mut [f64],
2202    ) -> Result<()> {
2203        if x.len() < m_samples * m_features {
2204            return Err(Error::InvalidArgument(format!(
2205                "PCA transform: x length {} < m_samples·m_features = {}",
2206                x.len(),
2207                m_samples * m_features
2208            )));
2209        }
2210        if out.len() < m_samples * n_components {
2211            return Err(Error::InvalidArgument(format!(
2212                "PCA transform: out length {} < m_samples·n_components = {}",
2213                out.len(),
2214                m_samples * n_components
2215            )));
2216        }
2217        let status = unsafe {
2218            sys::da_pca_transform_d(
2219                self.handle.raw,
2220                m_samples as sys::da_int,
2221                m_features as sys::da_int,
2222                x.as_ptr(),
2223                m_samples as sys::da_int,
2224                out.as_mut_ptr(),
2225                m_samples as sys::da_int,
2226            )
2227        };
2228        check_status("data-analytics", status)
2229    }
2230}
2231
2232impl std::fmt::Debug for Pca {
2233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2234        f.debug_struct("Pca").field("handle", &self.handle).finish()
2235    }
2236}
2237
2238// ---------------------------------------------------------------------------
2239//   Width-correct integer buffers
2240// ---------------------------------------------------------------------------
2241//
2242// The safe API takes and returns `i32` labels, indices and class ids, but the library's `da_int` is 32-bit under LP64
2243// and 64-bit under ILP64. Handing it a pointer cast from an `i32` slice is only right for LP64 (under ILP64 it reads
2244// and writes 8 bytes per element: measured, an access violation), so every integer array goes through a `da_int`
2245// buffer and is narrowed back with a range check.
2246
2247/// Copy `i32` values into a `da_int` buffer.
2248fn ints_in(x: &[i32]) -> Vec<sys::da_int> {
2249    x.iter().map(|&v| v as sys::da_int).collect()
2250}
2251
2252/// A `da_int` output buffer that is narrowed back into the caller's `&mut [i32]`.
2253struct IntsOut {
2254    buf: Vec<sys::da_int>,
2255}
2256
2257impl IntsOut {
2258    fn new(len: usize) -> Self {
2259        Self {
2260            buf: vec![0; len.max(1)],
2261        }
2262    }
2263    fn as_mut_ptr(&mut self) -> *mut sys::da_int {
2264        self.buf.as_mut_ptr()
2265    }
2266    /// Copy the first `n` results into `out`, failing if a value does not fit in `i32`.
2267    fn write_back(&self, out: &mut [i32], n: usize) -> Result<()> {
2268        for (o, &v) in out.iter_mut().zip(self.buf.iter()).take(n) {
2269            *o = i32::try_from(v).map_err(|_| {
2270                Error::InvalidArgument(format!(
2271                    "the library returned {v}, which does not fit in i32"
2272                ))
2273            })?;
2274        }
2275        Ok(())
2276    }
2277}
2278
2279/// k-nearest-neighbours classifier.
2280pub struct KNearestNeighbours {
2281    handle: Handle,
2282    // `da_nn_set_data_d` / `da_nn_set_labels_d` store pointers, not copies, so the training data is owned here.
2283    train_x: Vec<f64>,
2284    train_y: Vec<sys::da_int>,
2285}
2286
2287impl KNearestNeighbours {
2288    /// Build a new k-NN classifier in `f64` precision. The number of
2289    /// neighbours `k` defaults to AOCL-DA's built-in default (commonly
2290    /// 5); call [`KNearestNeighbours::handle_mut`] and
2291    /// `set_int_option` to override it (the option name is AOCL-version
2292    /// specific — try `"number of neighbours"`).
2293    pub fn new() -> Result<Self> {
2294        let handle = Handle::new_double(HandleKind::Knn)?;
2295        Ok(Self {
2296            handle,
2297            train_x: Vec::new(),
2298            train_y: Vec::new(),
2299        })
2300    }
2301
2302    /// Borrow the underlying handle to set algorithm-specific options.
2303    pub fn handle_mut(&mut self) -> &mut Handle {
2304        &mut self.handle
2305    }
2306
2307    /// Fit with `n_samples × n_features` training data (column-major)
2308    /// and a `n_samples` integer label vector.
2309    pub fn fit(
2310        &mut self,
2311        n_samples: usize,
2312        n_features: usize,
2313        x_train: &[f64],
2314        y_train: &[i32],
2315    ) -> Result<()> {
2316        if x_train.len() < n_samples * n_features {
2317            return Err(Error::InvalidArgument(format!(
2318                "knn fit: x_train length {} < n_samples·n_features = {}",
2319                x_train.len(),
2320                n_samples * n_features
2321            )));
2322        }
2323        if y_train.len() < n_samples {
2324            return Err(Error::InvalidArgument(format!(
2325                "knn fit: y_train length {} < n_samples = {n_samples}",
2326                y_train.len()
2327            )));
2328        }
2329        self.train_x = x_train[..n_samples * n_features].to_vec();
2330        self.train_y = ints_in(&y_train[..n_samples]);
2331        let status = unsafe {
2332            sys::da_nn_set_data_d(
2333                self.handle.raw,
2334                n_samples as sys::da_int,
2335                n_features as sys::da_int,
2336                self.train_x.as_ptr(),
2337                n_samples as sys::da_int,
2338            )
2339        };
2340        check_status("data-analytics", status)?;
2341        let status = unsafe {
2342            sys::da_nn_set_labels_d(
2343                self.handle.raw,
2344                n_samples as sys::da_int,
2345                self.train_y.as_ptr(),
2346            )
2347        };
2348        check_status("data-analytics", status)
2349    }
2350
2351    /// Predict labels for `n_queries × n_features` samples (column-major).
2352    pub fn predict(
2353        &mut self,
2354        n_queries: usize,
2355        n_features: usize,
2356        x_test: &[f64],
2357        labels: &mut [i32],
2358    ) -> Result<()> {
2359        if x_test.len() < n_queries * n_features {
2360            return Err(Error::InvalidArgument(format!(
2361                "knn predict: x_test length {} < n_queries·n_features = {}",
2362                x_test.len(),
2363                n_queries * n_features
2364            )));
2365        }
2366        if labels.len() < n_queries {
2367            return Err(Error::InvalidArgument(format!(
2368                "knn predict: labels length {} < n_queries = {n_queries}",
2369                labels.len()
2370            )));
2371        }
2372        let mut out = IntsOut::new(n_queries);
2373        let status = unsafe {
2374            sys::da_nn_classifier_predict_d(
2375                self.handle.raw,
2376                n_queries as sys::da_int,
2377                n_features as sys::da_int,
2378                x_test.as_ptr(),
2379                n_queries as sys::da_int,
2380                out.as_mut_ptr(),
2381                sys::da_nn_search_mode__knn_search_mode,
2382            )
2383        };
2384        check_status("data-analytics", status)?;
2385        out.write_back(labels, n_queries)
2386    }
2387
2388    /// For each of `n_queries` test rows, write into `n_ind` (length
2389    /// `n_queries · k`) the column-major indices of its `k` nearest
2390    /// training-set neighbours. If `return_distance` is true, also fill
2391    /// `n_dist` (same shape) with the distances.
2392    pub fn kneighbors(
2393        &mut self,
2394        n_queries: usize,
2395        n_features: usize,
2396        x_test: &[f64],
2397        n_ind: &mut [i32],
2398        n_dist: &mut [f64],
2399        k: usize,
2400        return_distance: bool,
2401    ) -> Result<()> {
2402        check_dense(
2403            "kneighbors",
2404            "x_test",
2405            Layout::ColMajor,
2406            n_queries,
2407            n_features,
2408            n_queries,
2409            x_test.len(),
2410        )?;
2411        if n_ind.len() < n_queries * k {
2412            return Err(Error::InvalidArgument(format!(
2413                "kneighbors: n_ind has {} elements, {} are needed",
2414                n_ind.len(),
2415                n_queries * k
2416            )));
2417        }
2418        if return_distance {
2419            check_dense(
2420                "kneighbors",
2421                "n_dist",
2422                Layout::ColMajor,
2423                n_queries,
2424                k,
2425                n_queries,
2426                n_dist.len(),
2427            )?;
2428        }
2429        let mut out = IntsOut::new(n_ind.len());
2430        let status = unsafe {
2431            sys::da_nn_kneighbors_d(
2432                self.handle.raw,
2433                n_queries as sys::da_int,
2434                n_features as sys::da_int,
2435                x_test.as_ptr(),
2436                n_queries as sys::da_int,
2437                out.as_mut_ptr(),
2438                n_dist.as_mut_ptr(),
2439                k as sys::da_int,
2440                if return_distance { 1 } else { 0 } as sys::da_int,
2441            )
2442        };
2443        check_status("data-analytics", status)?;
2444        out.write_back(n_ind, n_queries * k)
2445    }
2446
2447    /// Retrieve the unique class labels seen during training, ascending,
2448    /// into `classes` (at most `classes.len()` of them). Returns the
2449    /// number of classes, which may exceed `classes.len()`.
2450    pub fn classes(&self, classes: &mut [i32]) -> Result<usize> {
2451        // `n_classes` is in/out: a value > 0 on entry is taken as the number of classes (the library then writes that
2452        // many entries, past its own array when the caller's buffer is merely large), so ask for the count with 0 first.
2453        let mut n_classes: sys::da_int = 0;
2454        let status =
2455            unsafe { sys::da_nn_classes_d(self.handle.raw, &mut n_classes, std::ptr::null_mut()) };
2456        check_status("data-analytics", status)?;
2457        let total = n_classes.max(0) as usize;
2458        if total == 0 {
2459            return Ok(0);
2460        }
2461        let mut out = IntsOut::new(total);
2462        let mut n_again: sys::da_int = total as sys::da_int;
2463        let status =
2464            unsafe { sys::da_nn_classes_d(self.handle.raw, &mut n_again, out.as_mut_ptr()) };
2465        check_status("data-analytics", status)?;
2466        out.write_back(classes, total.min(classes.len()))?;
2467        Ok(total)
2468    }
2469
2470    /// Probability estimates: `n_queries × n_classes` column-major matrix
2471    /// at `proba` (element (query, class) at `class * n_queries + query`). Use [`KNearestNeighbours::classes`] to discover
2472    /// which class each column corresponds to.
2473    pub fn predict_proba(
2474        &mut self,
2475        n_queries: usize,
2476        n_features: usize,
2477        x_test: &[f64],
2478        proba: &mut [f64],
2479    ) -> Result<()> {
2480        check_dense(
2481            "predict_proba",
2482            "x_test",
2483            Layout::ColMajor,
2484            n_queries,
2485            n_features,
2486            n_queries,
2487            x_test.len(),
2488        )?;
2489        let n_classes = {
2490            let mut c = self.train_y.clone();
2491            c.sort_unstable();
2492            c.dedup();
2493            c.len()
2494        };
2495        check_dense(
2496            "predict_proba",
2497            "proba",
2498            Layout::ColMajor,
2499            n_queries,
2500            n_classes,
2501            n_queries,
2502            proba.len(),
2503        )?;
2504        let status = unsafe {
2505            sys::da_nn_classifier_predict_proba_d(
2506                self.handle.raw,
2507                n_queries as sys::da_int,
2508                n_features as sys::da_int,
2509                x_test.as_ptr(),
2510                n_queries as sys::da_int,
2511                proba.as_mut_ptr(),
2512                sys::da_nn_search_mode__knn_search_mode,
2513            )
2514        };
2515        check_status("data-analytics", status)
2516    }
2517}
2518
2519impl std::fmt::Debug for KNearestNeighbours {
2520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2521        f.debug_struct("KNearestNeighbours")
2522            .field("handle", &self.handle)
2523            .finish()
2524    }
2525}
2526
2527// =========================================================================
2528//   Linear models (linmod)
2529// =========================================================================
2530
2531/// Family of linear model handled by [`Linmod`].
2532#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2533#[non_exhaustive]
2534pub enum LinmodKind {
2535    /// L2 (least-squares) linear regression.
2536    Mse,
2537    /// Logistic regression for classification.
2538    Logistic,
2539}
2540
2541impl LinmodKind {
2542    fn raw(self) -> sys::linmod_model {
2543        match self {
2544            LinmodKind::Mse => sys::linmod_model__linmod_model_mse,
2545            LinmodKind::Logistic => sys::linmod_model__linmod_model_logistic,
2546        }
2547    }
2548}
2549
2550/// Linear-model wrapper covering least-squares (MSE) regression and
2551/// logistic regression. Use [`Linmod::fit`] to fit the model on training
2552/// data, then [`Linmod::coefficients`] to inspect the fitted weights or
2553/// [`Linmod::predict`] / [`Linmod::evaluate`] to apply the model.
2554///
2555/// Data is laid out **column-major** by default (one column per feature,
2556/// `lda = n_samples`). To pass row-major data, call
2557/// [`Linmod::handle_mut`] and `set_string_option("storage order",
2558/// "row-major")` before fitting.
2559pub struct Linmod {
2560    handle: Handle,
2561    kind: LinmodKind,
2562    n_features_at_fit: Option<usize>,
2563}
2564
2565impl Linmod {
2566    /// Build a new MSE (L2) regression model in `f64` precision.
2567    pub fn new_mse() -> Result<Self> {
2568        Self::new_with(LinmodKind::Mse)
2569    }
2570
2571    /// Build a new logistic regression model in `f64` precision.
2572    pub fn new_logistic() -> Result<Self> {
2573        Self::new_with(LinmodKind::Logistic)
2574    }
2575
2576    fn new_with(kind: LinmodKind) -> Result<Self> {
2577        let handle = Handle::new_double(HandleKind::Linmod)?;
2578        let status = unsafe { sys::da_linmod_select_model_d(handle.raw, kind.raw()) };
2579        check_status("data-analytics", status)?;
2580        Ok(Self {
2581            handle,
2582            kind,
2583            n_features_at_fit: None,
2584        })
2585    }
2586
2587    /// Borrow the underlying handle to set algorithm-specific options
2588    /// (regularisation, solver choice, storage order, …).
2589    pub fn handle_mut(&mut self) -> &mut Handle {
2590        &mut self.handle
2591    }
2592
2593    /// Family of linear model that this handle was constructed for.
2594    pub fn kind(&self) -> LinmodKind {
2595        self.kind
2596    }
2597
2598    /// Fit the model on `n_samples × n_features` training data (column-major
2599    /// by default) with a length-`n_samples` response vector `y`.
2600    pub fn fit(&mut self, n_samples: usize, n_features: usize, x: &[f64], y: &[f64]) -> Result<()> {
2601        if x.len() < n_samples * n_features {
2602            return Err(Error::InvalidArgument(format!(
2603                "linmod fit: x length {} < n_samples·n_features = {}",
2604                x.len(),
2605                n_samples * n_features
2606            )));
2607        }
2608        if y.len() < n_samples {
2609            return Err(Error::InvalidArgument(format!(
2610                "linmod fit: y length {} < n_samples = {n_samples}",
2611                y.len()
2612            )));
2613        }
2614        let status = unsafe {
2615            sys::da_linmod_define_features_d(
2616                self.handle.raw,
2617                n_samples as sys::da_int,
2618                n_features as sys::da_int,
2619                x.as_ptr(),
2620                n_samples as sys::da_int, // ldx: column-major, the default storage order
2621                y.as_ptr(),
2622            )
2623        };
2624        if status != sys::da_status__da_status_success {
2625            self.handle.note_status(status);
2626            let extra = self.handle.last_error_message().unwrap_or_default();
2627            return Err(Error::Status {
2628                component: "data-analytics",
2629                code: status as i64,
2630                message: format!("linmod define_features failed: {extra}"),
2631            });
2632        }
2633        let status = unsafe { sys::da_linmod_fit_d(self.handle.raw) };
2634        if status != sys::da_status__da_status_success {
2635            self.handle.note_status(status);
2636            let extra = self.handle.last_error_message().unwrap_or_default();
2637            return Err(Error::Status {
2638                component: "data-analytics",
2639                code: status as i64,
2640                message: format!("linmod fit failed: {extra}"),
2641            });
2642        }
2643        self.n_features_at_fit = Some(n_features);
2644        Ok(())
2645    }
2646
2647    /// Retrieve the fitted model coefficients. For MSE regression with no
2648    /// intercept this is a vector of length `n_features`; with an intercept
2649    /// or for logistic regression it may be longer (the library decides
2650    /// the layout).
2651    pub fn coefficients(&self) -> Result<Vec<f64>> {
2652        // AOCL's size-discovery pattern: call with a buffer that may be
2653        // too small. On `invalid_array_dimension`, `dim` is updated with
2654        // the required size; resize and call again.
2655        let mut dim: sys::da_int = 1;
2656        let mut tmp = [0.0_f64; 1];
2657        let probe = unsafe {
2658            sys::da_handle_get_result_d(
2659                self.handle.raw,
2660                sys::da_result__da_linmod_coef,
2661                &mut dim,
2662                tmp.as_mut_ptr(),
2663            )
2664        };
2665        if probe == sys::da_status__da_status_success {
2666            return Ok(tmp[..dim as usize].to_vec());
2667        }
2668        if probe != sys::da_status__da_status_invalid_array_dimension {
2669            self.handle.note_status(probe);
2670            let extra = self.handle.last_error_message().unwrap_or_default();
2671            return Err(Error::Status {
2672                component: "data-analytics",
2673                code: probe as i64,
2674                message: format!("linmod coefficients (probe): {extra}"),
2675            });
2676        }
2677        if dim <= 0 {
2678            return Err(Error::Status {
2679                component: "data-analytics",
2680                code: probe as i64,
2681                message: "linmod coefficients: solver did not report a size".into(),
2682            });
2683        }
2684        let mut out = vec![0.0_f64; dim as usize];
2685        let status = unsafe {
2686            sys::da_handle_get_result_d(
2687                self.handle.raw,
2688                sys::da_result__da_linmod_coef,
2689                &mut dim,
2690                out.as_mut_ptr(),
2691            )
2692        };
2693        if status != sys::da_status__da_status_success {
2694            self.handle.note_status(status);
2695            let extra = self.handle.last_error_message().unwrap_or_default();
2696            return Err(Error::Status {
2697                component: "data-analytics",
2698                code: status as i64,
2699                message: format!("linmod coefficients: {extra}"),
2700            });
2701        }
2702        out.truncate(dim as usize);
2703        Ok(out)
2704    }
2705
2706    /// Apply the model to `n_samples × n_features` new data, writing
2707    /// `n_samples` predicted values into `predictions`. For MSE regression
2708    /// these are continuous responses; for logistic regression they are
2709    /// integer class indices stored as floats.
2710    pub fn predict(
2711        &mut self,
2712        n_samples: usize,
2713        n_features: usize,
2714        x: &[f64],
2715        predictions: &mut [f64],
2716    ) -> Result<()> {
2717        if let Some(expected) = self.n_features_at_fit {
2718            if expected != n_features {
2719                return Err(Error::InvalidArgument(format!(
2720                    "linmod predict: n_features {n_features} != fit-time {expected}"
2721                )));
2722            }
2723        }
2724        if x.len() < n_samples * n_features {
2725            return Err(Error::InvalidArgument(format!(
2726                "linmod predict: x length {} < n_samples·n_features = {}",
2727                x.len(),
2728                n_samples * n_features
2729            )));
2730        }
2731        if predictions.len() < n_samples {
2732            return Err(Error::InvalidArgument(format!(
2733                "linmod predict: predictions length {} < n_samples = {n_samples}",
2734                predictions.len()
2735            )));
2736        }
2737        let status = unsafe {
2738            sys::da_linmod_evaluate_model_d(
2739                self.handle.raw,
2740                n_samples as sys::da_int,
2741                n_features as sys::da_int,
2742                x.as_ptr(),
2743                n_samples as sys::da_int, // ldx: column-major, the default storage order
2744                predictions.as_mut_ptr(),
2745                std::ptr::null_mut(),
2746                std::ptr::null_mut(),
2747            )
2748        };
2749        check_status("data-analytics", status)
2750    }
2751
2752    /// Apply the model and also compute the model loss against the
2753    /// supplied observations `y`. Returns the scalar loss.
2754    pub fn evaluate(
2755        &mut self,
2756        n_samples: usize,
2757        n_features: usize,
2758        x: &[f64],
2759        y: &[f64],
2760        predictions: &mut [f64],
2761    ) -> Result<f64> {
2762        if y.len() < n_samples {
2763            return Err(Error::InvalidArgument(format!(
2764                "linmod evaluate: y length {} < n_samples = {n_samples}",
2765                y.len()
2766            )));
2767        }
2768        if x.len() < n_samples * n_features {
2769            return Err(Error::InvalidArgument(format!(
2770                "linmod evaluate: x length {} < n_samples·n_features = {}",
2771                x.len(),
2772                n_samples * n_features
2773            )));
2774        }
2775        if predictions.len() < n_samples {
2776            return Err(Error::InvalidArgument(format!(
2777                "linmod evaluate: predictions length {} < n_samples = {n_samples}",
2778                predictions.len()
2779            )));
2780        }
2781        // The C API takes `observations` as *mut despite logically being
2782        // input; copy `y` into a local buffer to keep the callsite safe.
2783        let mut y_buf = y.to_vec();
2784        let mut loss = 0.0_f64;
2785        let status = unsafe {
2786            sys::da_linmod_evaluate_model_d(
2787                self.handle.raw,
2788                n_samples as sys::da_int,
2789                n_features as sys::da_int,
2790                x.as_ptr(),
2791                n_samples as sys::da_int, // ldx: column-major, the default storage order
2792                predictions.as_mut_ptr(),
2793                y_buf.as_mut_ptr(),
2794                &mut loss,
2795            )
2796        };
2797        check_status("data-analytics", status)?;
2798        Ok(loss)
2799    }
2800}
2801
2802impl std::fmt::Debug for Linmod {
2803    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2804        f.debug_struct("Linmod")
2805            .field("kind", &self.kind)
2806            .field("handle", &self.handle)
2807            .finish()
2808    }
2809}
2810
2811// =========================================================================
2812//   DBSCAN clustering
2813// =========================================================================
2814
2815/// DBSCAN density-based clustering. Unlike k-means it does not require
2816/// the number of clusters in advance and can mark points as noise
2817/// (label `-1`).
2818///
2819/// Configure with options like `"eps"` and `"min_samples"` via
2820/// [`Dbscan::handle_mut`] before [`Dbscan::fit`]; defaults follow
2821/// scikit-learn's conventions.
2822pub struct Dbscan {
2823    handle: Handle,
2824    n_samples_at_fit: Option<usize>,
2825}
2826
2827impl Dbscan {
2828    /// Build a new DBSCAN handle in `f64` precision.
2829    pub fn new() -> Result<Self> {
2830        let handle = Handle::new_double(HandleKind::Dbscan)?;
2831        Ok(Self {
2832            handle,
2833            n_samples_at_fit: None,
2834        })
2835    }
2836
2837    /// Borrow the underlying handle to set DBSCAN-specific options:
2838    /// e.g. `set_string_option("metric", "euclidean")`,
2839    /// `set_int_option("min samples", 5)`, or for the real-valued
2840    /// `eps` use `da_options_set_real_d` directly via [`Handle::as_raw`].
2841    pub fn handle_mut(&mut self) -> &mut Handle {
2842        &mut self.handle
2843    }
2844
2845    /// Fit on column-major `n_samples × n_features` data matrix.
2846    pub fn fit(&mut self, n_samples: usize, n_features: usize, data: &[f64]) -> Result<()> {
2847        if data.len() < n_samples * n_features {
2848            return Err(Error::InvalidArgument(format!(
2849                "dbscan fit: data length {} < n_samples·n_features = {}",
2850                data.len(),
2851                n_samples * n_features
2852            )));
2853        }
2854        let lda = n_samples;
2855        let status = unsafe {
2856            sys::da_dbscan_set_data_d(
2857                self.handle.raw,
2858                n_samples as sys::da_int,
2859                n_features as sys::da_int,
2860                data.as_ptr(),
2861                lda as sys::da_int,
2862            )
2863        };
2864        if status != sys::da_status__da_status_success {
2865            self.handle.note_status(status);
2866            let extra = self.handle.last_error_message().unwrap_or_default();
2867            return Err(Error::Status {
2868                component: "data-analytics",
2869                code: status as i64,
2870                message: format!("dbscan set_data failed: {extra}"),
2871            });
2872        }
2873        let status = unsafe { sys::da_dbscan_compute_d(self.handle.raw) };
2874        if status != sys::da_status__da_status_success {
2875            self.handle.note_status(status);
2876            let extra = self.handle.last_error_message().unwrap_or_default();
2877            return Err(Error::Status {
2878                component: "data-analytics",
2879                code: status as i64,
2880                message: format!("dbscan compute failed: {extra}"),
2881            });
2882        }
2883        self.n_samples_at_fit = Some(n_samples);
2884        Ok(())
2885    }
2886
2887    /// Number of clusters discovered (excludes noise).
2888    pub fn n_clusters(&self) -> Result<usize> {
2889        let mut dim: sys::da_int = 1;
2890        let mut buf = [0_i64 as sys::da_int; 1];
2891        let status = unsafe {
2892            sys::da_handle_get_result_int(
2893                self.handle.raw,
2894                sys::da_result__da_dbscan_n_clusters,
2895                &mut dim,
2896                buf.as_mut_ptr(),
2897            )
2898        };
2899        check_status("data-analytics", status)?;
2900        Ok(buf[0] as usize)
2901    }
2902
2903    /// Number of *core* samples (points that have at least `min_samples`
2904    /// neighbours within distance `eps`).
2905    pub fn n_core_samples(&self) -> Result<usize> {
2906        let mut dim: sys::da_int = 1;
2907        let mut buf = [0_i64 as sys::da_int; 1];
2908        let status = unsafe {
2909            sys::da_handle_get_result_int(
2910                self.handle.raw,
2911                sys::da_result__da_dbscan_n_core_samples,
2912                &mut dim,
2913                buf.as_mut_ptr(),
2914            )
2915        };
2916        check_status("data-analytics", status)?;
2917        Ok(buf[0] as usize)
2918    }
2919
2920    /// Labels assigned to each input sample. `-1` indicates noise; other
2921    /// values index a cluster `0 .. n_clusters()`.
2922    pub fn labels(&self) -> Result<Vec<i32>> {
2923        let n = self.n_samples_at_fit.ok_or_else(|| {
2924            Error::InvalidArgument("dbscan labels: model has not been fit yet".into())
2925        })?;
2926        let mut dim: sys::da_int = n as sys::da_int;
2927        let mut out: Vec<sys::da_int> = vec![0; n];
2928        let status = unsafe {
2929            sys::da_handle_get_result_int(
2930                self.handle.raw,
2931                sys::da_result__da_dbscan_labels,
2932                &mut dim,
2933                out.as_mut_ptr(),
2934            )
2935        };
2936        check_status("data-analytics", status)?;
2937        out.truncate(dim as usize);
2938        Ok(out.into_iter().map(|v| v as i32).collect())
2939    }
2940
2941    /// Indices of the core samples (length = `n_core_samples()`).
2942    pub fn core_sample_indices(&self) -> Result<Vec<i32>> {
2943        let n_core = self.n_core_samples()?;
2944        let mut dim: sys::da_int = n_core as sys::da_int;
2945        let mut out: Vec<sys::da_int> = vec![0; n_core];
2946        if n_core == 0 {
2947            return Ok(Vec::new());
2948        }
2949        let status = unsafe {
2950            sys::da_handle_get_result_int(
2951                self.handle.raw,
2952                sys::da_result__da_dbscan_core_sample_indices,
2953                &mut dim,
2954                out.as_mut_ptr(),
2955            )
2956        };
2957        check_status("data-analytics", status)?;
2958        out.truncate(dim as usize);
2959        Ok(out.into_iter().map(|v| v as i32).collect())
2960    }
2961}
2962
2963impl std::fmt::Debug for Dbscan {
2964    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2965        f.debug_struct("Dbscan")
2966            .field("handle", &self.handle)
2967            .finish()
2968    }
2969}
2970
2971// =========================================================================
2972//   Decision tree / forest
2973// =========================================================================
2974
2975/// A single decision tree classifier. Configure tree-specific options
2976/// such as `"maximum depth"` or `"minimum samples per split"` via
2977/// [`DecisionTree::handle_mut`] before calling [`DecisionTree::fit`].
2978pub struct DecisionTree {
2979    handle: Handle,
2980}
2981
2982impl DecisionTree {
2983    /// Build a new decision-tree handle in `f64` precision.
2984    pub fn new() -> Result<Self> {
2985        let handle = Handle::new_double(HandleKind::DecisionTree)?;
2986        Ok(Self { handle })
2987    }
2988
2989    /// Borrow the underlying handle to set tree options.
2990    pub fn handle_mut(&mut self) -> &mut Handle {
2991        &mut self.handle
2992    }
2993
2994    /// Fit on column-major `n_samples × n_features` features `x` with
2995    /// integer class labels `y`. `n_class = 0` lets AOCL infer it from
2996    /// the label distribution.
2997    pub fn fit(
2998        &mut self,
2999        n_samples: usize,
3000        n_features: usize,
3001        n_class: usize,
3002        x: &[f64],
3003        y: &[i32],
3004    ) -> Result<()> {
3005        if x.len() < n_samples * n_features {
3006            return Err(Error::InvalidArgument(format!(
3007                "tree fit: x length {} < n_samples·n_features = {}",
3008                x.len(),
3009                n_samples * n_features
3010            )));
3011        }
3012        if y.len() < n_samples {
3013            return Err(Error::InvalidArgument(format!(
3014                "tree fit: y length {} < n_samples = {n_samples}",
3015                y.len()
3016            )));
3017        }
3018        let lda = n_samples;
3019        let y_da = ints_in(&y[..n_samples]);
3020        let status = unsafe {
3021            sys::da_tree_set_training_data_d(
3022                self.handle.raw,
3023                n_samples as sys::da_int,
3024                n_features as sys::da_int,
3025                n_class as sys::da_int,
3026                x.as_ptr(),
3027                lda as sys::da_int,
3028                y_da.as_ptr(),
3029                std::ptr::null(), // categorical_features: none (argument added in AOCL 5.3)
3030            )
3031        };
3032        if status != sys::da_status__da_status_success {
3033            self.handle.note_status(status);
3034            let extra = self.handle.last_error_message().unwrap_or_default();
3035            return Err(Error::Status {
3036                component: "data-analytics",
3037                code: status as i64,
3038                message: format!("tree set_training_data failed: {extra}"),
3039            });
3040        }
3041        let status = unsafe { sys::da_tree_fit_d(self.handle.raw) };
3042        if status != sys::da_status__da_status_success {
3043            self.handle.note_status(status);
3044            let extra = self.handle.last_error_message().unwrap_or_default();
3045            return Err(Error::Status {
3046                component: "data-analytics",
3047                code: status as i64,
3048                message: format!("tree fit failed: {extra}"),
3049            });
3050        }
3051        Ok(())
3052    }
3053
3054    /// Predict class labels for `n_samples × n_features` test data.
3055    pub fn predict(
3056        &mut self,
3057        n_samples: usize,
3058        n_features: usize,
3059        x_test: &[f64],
3060        labels: &mut [i32],
3061    ) -> Result<()> {
3062        if x_test.len() < n_samples * n_features {
3063            return Err(Error::InvalidArgument(format!(
3064                "tree predict: x_test length {} < n_samples·n_features = {}",
3065                x_test.len(),
3066                n_samples * n_features
3067            )));
3068        }
3069        if labels.len() < n_samples {
3070            return Err(Error::InvalidArgument(format!(
3071                "tree predict: labels length {} < n_samples = {n_samples}",
3072                labels.len()
3073            )));
3074        }
3075        let mut out = IntsOut::new(n_samples);
3076        let status = unsafe {
3077            sys::da_tree_predict_d(
3078                self.handle.raw,
3079                n_samples as sys::da_int,
3080                n_features as sys::da_int,
3081                x_test.as_ptr(),
3082                n_samples as sys::da_int,
3083                out.as_mut_ptr(),
3084            )
3085        };
3086        check_status("data-analytics", status)?;
3087        out.write_back(labels, n_samples)
3088    }
3089
3090    /// Compute prediction accuracy on a labelled test set: returns the
3091    /// fraction of correctly classified samples.
3092    pub fn score(
3093        &mut self,
3094        n_samples: usize,
3095        n_features: usize,
3096        x_test: &[f64],
3097        y_test: &[i32],
3098    ) -> Result<f64> {
3099        check_dense(
3100            "score",
3101            "x_test",
3102            Layout::ColMajor,
3103            n_samples,
3104            n_features,
3105            n_samples,
3106            x_test.len(),
3107        )?;
3108        if y_test.len() < n_samples {
3109            return Err(Error::InvalidArgument(format!(
3110                "score: y_test length {} < n_samples = {n_samples}",
3111                y_test.len()
3112            )));
3113        }
3114        let y_da = ints_in(&y_test[..n_samples]);
3115        let mut acc = 0.0_f64;
3116        let status = unsafe {
3117            sys::da_tree_score_d(
3118                self.handle.raw,
3119                n_samples as sys::da_int,
3120                n_features as sys::da_int,
3121                x_test.as_ptr(),
3122                n_samples as sys::da_int,
3123                y_da.as_ptr(),
3124                &mut acc,
3125            )
3126        };
3127        check_status("data-analytics", status)?;
3128        Ok(acc)
3129    }
3130
3131    /// Predict class probabilities for `n_samples × n_features` test
3132    /// data. `y_proba` is `n_samples × n_class` in the handle's storage
3133    /// order (column-major, as for the features): element (sample `i`,
3134    /// class `c`) is at `c * ldy + i` with `ldy` ≥ `n_samples`.
3135    pub fn predict_proba(
3136        &mut self,
3137        n_samples: usize,
3138        n_features: usize,
3139        x_test: &[f64],
3140        y_proba: &mut [f64],
3141        n_class: usize,
3142        ldy: usize,
3143    ) -> Result<()> {
3144        check_dense(
3145            "predict_proba",
3146            "x_test",
3147            Layout::ColMajor,
3148            n_samples,
3149            n_features,
3150            n_samples,
3151            x_test.len(),
3152        )?;
3153        check_dense(
3154            "predict_proba",
3155            "y_proba",
3156            Layout::ColMajor,
3157            n_samples,
3158            n_class,
3159            ldy,
3160            y_proba.len(),
3161        )?;
3162        let status = unsafe {
3163            sys::da_tree_predict_proba_d(
3164                self.handle.raw,
3165                n_samples as sys::da_int,
3166                n_features as sys::da_int,
3167                x_test.as_ptr(),
3168                n_samples as sys::da_int,
3169                y_proba.as_mut_ptr(),
3170                n_class as sys::da_int,
3171                ldy as sys::da_int,
3172            )
3173        };
3174        check_status("data-analytics", status)
3175    }
3176
3177    /// Predict log class probabilities. See [`DecisionTree::predict_proba`].
3178    pub fn predict_log_proba(
3179        &mut self,
3180        n_samples: usize,
3181        n_features: usize,
3182        x_test: &[f64],
3183        y_log_proba: &mut [f64],
3184        n_class: usize,
3185        ldy: usize,
3186    ) -> Result<()> {
3187        check_dense(
3188            "predict_log_proba",
3189            "x_test",
3190            Layout::ColMajor,
3191            n_samples,
3192            n_features,
3193            n_samples,
3194            x_test.len(),
3195        )?;
3196        check_dense(
3197            "predict_log_proba",
3198            "y_log_proba",
3199            Layout::ColMajor,
3200            n_samples,
3201            n_class,
3202            ldy,
3203            y_log_proba.len(),
3204        )?;
3205        let status = unsafe {
3206            sys::da_tree_predict_log_proba_d(
3207                self.handle.raw,
3208                n_samples as sys::da_int,
3209                n_features as sys::da_int,
3210                x_test.as_ptr(),
3211                n_samples as sys::da_int,
3212                y_log_proba.as_mut_ptr(),
3213                n_class as sys::da_int,
3214                ldy as sys::da_int,
3215            )
3216        };
3217        check_status("data-analytics", status)
3218    }
3219}
3220
3221impl std::fmt::Debug for DecisionTree {
3222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3223        f.debug_struct("DecisionTree")
3224            .field("handle", &self.handle)
3225            .finish()
3226    }
3227}
3228
3229/// A random-forest classifier. Configure forest options such as
3230/// `"number of trees"` or `"bootstrap"` via [`DecisionForest::handle_mut`]
3231/// before calling [`DecisionForest::fit`].
3232pub struct DecisionForest {
3233    handle: Handle,
3234}
3235
3236impl DecisionForest {
3237    /// Build a new decision-forest handle in `f64` precision.
3238    pub fn new() -> Result<Self> {
3239        let handle = Handle::new_double(HandleKind::DecisionForest)?;
3240        Ok(Self { handle })
3241    }
3242
3243    /// Borrow the underlying handle to set forest options.
3244    pub fn handle_mut(&mut self) -> &mut Handle {
3245        &mut self.handle
3246    }
3247
3248    /// Fit on column-major `n_samples × n_features` features `x` with
3249    /// integer class labels `y`. Pass `n_class = 0` to let AOCL infer it.
3250    pub fn fit(
3251        &mut self,
3252        n_samples: usize,
3253        n_features: usize,
3254        n_class: usize,
3255        x: &[f64],
3256        y: &[i32],
3257    ) -> Result<()> {
3258        if x.len() < n_samples * n_features {
3259            return Err(Error::InvalidArgument(format!(
3260                "forest fit: x length {} < n_samples·n_features = {}",
3261                x.len(),
3262                n_samples * n_features
3263            )));
3264        }
3265        if y.len() < n_samples {
3266            return Err(Error::InvalidArgument(format!(
3267                "forest fit: y length {} < n_samples = {n_samples}",
3268                y.len()
3269            )));
3270        }
3271        let lda = n_samples;
3272        let y_da = ints_in(&y[..n_samples]);
3273        let status = unsafe {
3274            sys::da_forest_set_training_data_d(
3275                self.handle.raw,
3276                n_samples as sys::da_int,
3277                n_features as sys::da_int,
3278                n_class as sys::da_int,
3279                x.as_ptr(),
3280                lda as sys::da_int,
3281                y_da.as_ptr(),
3282                std::ptr::null(), // categorical_features: none (argument added in AOCL 5.3)
3283            )
3284        };
3285        if status != sys::da_status__da_status_success {
3286            self.handle.note_status(status);
3287            let extra = self.handle.last_error_message().unwrap_or_default();
3288            return Err(Error::Status {
3289                component: "data-analytics",
3290                code: status as i64,
3291                message: format!("forest set_training_data failed: {extra}"),
3292            });
3293        }
3294        let status = unsafe { sys::da_forest_fit_d(self.handle.raw) };
3295        if status != sys::da_status__da_status_success {
3296            self.handle.note_status(status);
3297            let extra = self.handle.last_error_message().unwrap_or_default();
3298            return Err(Error::Status {
3299                component: "data-analytics",
3300                code: status as i64,
3301                message: format!("forest fit failed: {extra}"),
3302            });
3303        }
3304        Ok(())
3305    }
3306
3307    /// Predict class labels for `n_samples × n_features` test data.
3308    pub fn predict(
3309        &mut self,
3310        n_samples: usize,
3311        n_features: usize,
3312        x_test: &[f64],
3313        labels: &mut [i32],
3314    ) -> Result<()> {
3315        if x_test.len() < n_samples * n_features {
3316            return Err(Error::InvalidArgument(format!(
3317                "forest predict: x_test length {} < n_samples·n_features = {}",
3318                x_test.len(),
3319                n_samples * n_features
3320            )));
3321        }
3322        if labels.len() < n_samples {
3323            return Err(Error::InvalidArgument(format!(
3324                "forest predict: labels length {} < n_samples = {n_samples}",
3325                labels.len()
3326            )));
3327        }
3328        let mut out = IntsOut::new(n_samples);
3329        let status = unsafe {
3330            sys::da_forest_predict_d(
3331                self.handle.raw,
3332                n_samples as sys::da_int,
3333                n_features as sys::da_int,
3334                x_test.as_ptr(),
3335                n_samples as sys::da_int,
3336                out.as_mut_ptr(),
3337            )
3338        };
3339        check_status("data-analytics", status)?;
3340        out.write_back(labels, n_samples)
3341    }
3342
3343    /// Compute prediction accuracy on a labelled test set.
3344    pub fn score(
3345        &mut self,
3346        n_samples: usize,
3347        n_features: usize,
3348        x_test: &[f64],
3349        y_test: &[i32],
3350    ) -> Result<f64> {
3351        check_dense(
3352            "score",
3353            "x_test",
3354            Layout::ColMajor,
3355            n_samples,
3356            n_features,
3357            n_samples,
3358            x_test.len(),
3359        )?;
3360        if y_test.len() < n_samples {
3361            return Err(Error::InvalidArgument(format!(
3362                "score: y_test length {} < n_samples = {n_samples}",
3363                y_test.len()
3364            )));
3365        }
3366        let y_da = ints_in(&y_test[..n_samples]);
3367        let mut acc = 0.0_f64;
3368        let status = unsafe {
3369            sys::da_forest_score_d(
3370                self.handle.raw,
3371                n_samples as sys::da_int,
3372                n_features as sys::da_int,
3373                x_test.as_ptr(),
3374                n_samples as sys::da_int,
3375                y_da.as_ptr(),
3376                &mut acc,
3377            )
3378        };
3379        check_status("data-analytics", status)?;
3380        Ok(acc)
3381    }
3382
3383    /// Predict class probabilities for the random forest. See
3384    /// [`DecisionTree::predict_proba`].
3385    pub fn predict_proba(
3386        &mut self,
3387        n_samples: usize,
3388        n_features: usize,
3389        x_test: &[f64],
3390        y_proba: &mut [f64],
3391        n_class: usize,
3392        ldy: usize,
3393    ) -> Result<()> {
3394        check_dense(
3395            "predict_proba",
3396            "x_test",
3397            Layout::ColMajor,
3398            n_samples,
3399            n_features,
3400            n_samples,
3401            x_test.len(),
3402        )?;
3403        check_dense(
3404            "predict_proba",
3405            "y_proba",
3406            Layout::ColMajor,
3407            n_samples,
3408            n_class,
3409            ldy,
3410            y_proba.len(),
3411        )?;
3412        let status = unsafe {
3413            sys::da_forest_predict_proba_d(
3414                self.handle.raw,
3415                n_samples as sys::da_int,
3416                n_features as sys::da_int,
3417                x_test.as_ptr(),
3418                n_samples as sys::da_int,
3419                y_proba.as_mut_ptr(),
3420                n_class as sys::da_int,
3421                ldy as sys::da_int,
3422            )
3423        };
3424        check_status("data-analytics", status)
3425    }
3426
3427    /// Predict log class probabilities for the random forest.
3428    pub fn predict_log_proba(
3429        &mut self,
3430        n_samples: usize,
3431        n_features: usize,
3432        x_test: &[f64],
3433        y_log_proba: &mut [f64],
3434        n_class: usize,
3435        ldy: usize,
3436    ) -> Result<()> {
3437        check_dense(
3438            "predict_log_proba",
3439            "x_test",
3440            Layout::ColMajor,
3441            n_samples,
3442            n_features,
3443            n_samples,
3444            x_test.len(),
3445        )?;
3446        check_dense(
3447            "predict_log_proba",
3448            "y_log_proba",
3449            Layout::ColMajor,
3450            n_samples,
3451            n_class,
3452            ldy,
3453            y_log_proba.len(),
3454        )?;
3455        let status = unsafe {
3456            sys::da_forest_predict_log_proba_d(
3457                self.handle.raw,
3458                n_samples as sys::da_int,
3459                n_features as sys::da_int,
3460                x_test.as_ptr(),
3461                n_samples as sys::da_int,
3462                y_log_proba.as_mut_ptr(),
3463                n_class as sys::da_int,
3464                ldy as sys::da_int,
3465            )
3466        };
3467        check_status("data-analytics", status)
3468    }
3469}
3470
3471impl std::fmt::Debug for DecisionForest {
3472    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3473        f.debug_struct("DecisionForest")
3474            .field("handle", &self.handle)
3475            .finish()
3476    }
3477}
3478
3479// =========================================================================
3480//   Support Vector Machines (SVM)
3481// =========================================================================
3482
3483/// Family of SVM model. Classification variants train against integer
3484/// class labels (passed as `f64`); regression variants train against a
3485/// real-valued response.
3486#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3487#[non_exhaustive]
3488pub enum SvmKind {
3489    /// C-regularised classification (`SVC`).
3490    Svc,
3491    /// Nu-regularised classification (`NuSVC`).
3492    NuSvc,
3493    /// Epsilon-regularised regression (`SVR`).
3494    Svr,
3495    /// Nu-regularised regression (`NuSVR`).
3496    NuSvr,
3497}
3498
3499impl SvmKind {
3500    fn raw(self) -> sys::da_svm_model {
3501        match self {
3502            SvmKind::Svc => sys::da_svm_model__svc,
3503            SvmKind::NuSvc => sys::da_svm_model__nusvc,
3504            SvmKind::Svr => sys::da_svm_model__svr,
3505            SvmKind::NuSvr => sys::da_svm_model__nusvr,
3506        }
3507    }
3508}
3509
3510/// Decision-function shape used for multi-class classification.
3511#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3512pub enum DecisionShape {
3513    /// One-vs-Rest.
3514    Ovr,
3515    /// One-vs-One.
3516    Ovo,
3517}
3518
3519impl DecisionShape {
3520    fn raw(self) -> sys::da_svm_decision_function_shape {
3521        match self {
3522            DecisionShape::Ovr => sys::da_svm_decision_function_shape__ovr,
3523            DecisionShape::Ovo => sys::da_svm_decision_function_shape__ovo,
3524        }
3525    }
3526}
3527
3528/// Support vector machine wrapper covering both classification (`Svc`,
3529/// `NuSvc`) and regression (`Svr`, `NuSvr`) modes. Configure
3530/// SVM-specific options (kernel, C, epsilon, gamma, …) via
3531/// [`Svm::handle_mut`] before calling [`Svm::fit`].
3532pub struct Svm {
3533    handle: Handle,
3534    kind: SvmKind,
3535    /// Number of distinct labels seen by `fit` (0 before a fit; classification models only), for the decision-function size.
3536    n_class: usize,
3537}
3538
3539impl Svm {
3540    /// Build a C-SVC classifier in `f64` precision.
3541    pub fn new_svc() -> Result<Self> {
3542        Self::new_with(SvmKind::Svc)
3543    }
3544    /// Build a Nu-SVC classifier in `f64` precision.
3545    pub fn new_nu_svc() -> Result<Self> {
3546        Self::new_with(SvmKind::NuSvc)
3547    }
3548    /// Build an epsilon-SVR regressor in `f64` precision.
3549    pub fn new_svr() -> Result<Self> {
3550        Self::new_with(SvmKind::Svr)
3551    }
3552    /// Build a Nu-SVR regressor in `f64` precision.
3553    pub fn new_nu_svr() -> Result<Self> {
3554        Self::new_with(SvmKind::NuSvr)
3555    }
3556
3557    fn new_with(kind: SvmKind) -> Result<Self> {
3558        let handle = Handle::new_double(HandleKind::Svm)?;
3559        let status = unsafe { sys::da_svm_select_model_d(handle.raw, kind.raw()) };
3560        check_status("data-analytics", status)?;
3561        Ok(Self {
3562            handle,
3563            kind,
3564            n_class: 0,
3565        })
3566    }
3567
3568    /// Borrow the underlying handle to set SVM-specific options.
3569    pub fn handle_mut(&mut self) -> &mut Handle {
3570        &mut self.handle
3571    }
3572
3573    /// Family of SVM model that this handle was constructed for.
3574    pub fn kind(&self) -> SvmKind {
3575        self.kind
3576    }
3577
3578    /// Fit on column-major `n_samples × n_features` features `x` and a
3579    /// length-`n_samples` response vector `y`. For classification, `y`
3580    /// holds class indices `0..n_class-1` (as floats); for regression
3581    /// it holds the real target.
3582    pub fn fit(&mut self, n_samples: usize, n_features: usize, x: &[f64], y: &[f64]) -> Result<()> {
3583        if x.len() < n_samples * n_features {
3584            return Err(Error::InvalidArgument(format!(
3585                "svm fit: x length {} < n_samples·n_features = {}",
3586                x.len(),
3587                n_samples * n_features
3588            )));
3589        }
3590        if y.len() < n_samples {
3591            return Err(Error::InvalidArgument(format!(
3592                "svm fit: y length {} < n_samples = {n_samples}",
3593                y.len()
3594            )));
3595        }
3596        if matches!(self.kind, SvmKind::Svc | SvmKind::NuSvc) {
3597            let mut c: Vec<i64> = y[..n_samples].iter().map(|v| *v as i64).collect();
3598            c.sort_unstable();
3599            c.dedup();
3600            self.n_class = c.len();
3601        }
3602        let lda = n_samples;
3603        let status = unsafe {
3604            sys::da_svm_set_data_d(
3605                self.handle.raw,
3606                n_samples as sys::da_int,
3607                n_features as sys::da_int,
3608                x.as_ptr(),
3609                lda as sys::da_int,
3610                y.as_ptr(),
3611            )
3612        };
3613        if status != sys::da_status__da_status_success {
3614            self.handle.note_status(status);
3615            let extra = self.handle.last_error_message().unwrap_or_default();
3616            return Err(Error::Status {
3617                component: "data-analytics",
3618                code: status as i64,
3619                message: format!("svm set_data failed: {extra}"),
3620            });
3621        }
3622        let status = unsafe { sys::da_svm_compute_d(self.handle.raw) };
3623        if status != sys::da_status__da_status_success {
3624            self.handle.note_status(status);
3625            let extra = self.handle.last_error_message().unwrap_or_default();
3626            return Err(Error::Status {
3627                component: "data-analytics",
3628                code: status as i64,
3629                message: format!("svm compute failed: {extra}"),
3630            });
3631        }
3632        Ok(())
3633    }
3634
3635    /// Predict labels (classification) or values (regression) for new
3636    /// data. `predictions` receives `n_samples` outputs.
3637    pub fn predict(
3638        &mut self,
3639        n_samples: usize,
3640        n_features: usize,
3641        x_test: &[f64],
3642        predictions: &mut [f64],
3643    ) -> Result<()> {
3644        if x_test.len() < n_samples * n_features {
3645            return Err(Error::InvalidArgument(format!(
3646                "svm predict: x_test length {} < n_samples·n_features = {}",
3647                x_test.len(),
3648                n_samples * n_features
3649            )));
3650        }
3651        if predictions.len() < n_samples {
3652            return Err(Error::InvalidArgument(format!(
3653                "svm predict: predictions length {} < n_samples = {n_samples}",
3654                predictions.len()
3655            )));
3656        }
3657        let status = unsafe {
3658            sys::da_svm_predict_d(
3659                self.handle.raw,
3660                n_samples as sys::da_int,
3661                n_features as sys::da_int,
3662                x_test.as_ptr(),
3663                n_samples as sys::da_int,
3664                predictions.as_mut_ptr(),
3665            )
3666        };
3667        check_status("data-analytics", status)
3668    }
3669
3670    /// Compute the model's score: accuracy for classification or `R²`
3671    /// for regression.
3672    pub fn score(
3673        &mut self,
3674        n_samples: usize,
3675        n_features: usize,
3676        x_test: &[f64],
3677        y_test: &[f64],
3678    ) -> Result<f64> {
3679        check_dense(
3680            "svm score",
3681            "x_test",
3682            Layout::ColMajor,
3683            n_samples,
3684            n_features,
3685            n_samples,
3686            x_test.len(),
3687        )?;
3688        if y_test.len() < n_samples {
3689            return Err(Error::InvalidArgument(format!(
3690                "svm score: y_test has {} elements, {n_samples} are needed",
3691                y_test.len()
3692            )));
3693        }
3694        let mut s = 0.0_f64;
3695        let status = unsafe {
3696            sys::da_svm_score_d(
3697                self.handle.raw,
3698                n_samples as sys::da_int,
3699                n_features as sys::da_int,
3700                x_test.as_ptr(),
3701                n_samples as sys::da_int,
3702                y_test.as_ptr(),
3703                &mut s,
3704            )
3705        };
3706        check_status("data-analytics", status)?;
3707        Ok(s)
3708    }
3709
3710    /// Compute the SVM decision function on test data (classification
3711    /// only; for regression call [`Svm::predict`] directly). Output
3712    /// layout depends on `shape` and `n_class`; see AOCL docs for the
3713    /// exact size requirements.
3714    pub fn decision_function(
3715        &mut self,
3716        n_samples: usize,
3717        n_features: usize,
3718        x_test: &[f64],
3719        shape: DecisionShape,
3720        decision_values: &mut [f64],
3721        ldd: usize,
3722    ) -> Result<()> {
3723        check_dense(
3724            "decision_function",
3725            "x_test",
3726            Layout::ColMajor,
3727            n_samples,
3728            n_features,
3729            n_samples,
3730            x_test.len(),
3731        )?;
3732        // columns: one per class pair for one-vs-one, one per class for one-vs-rest, a single column for two classes or a regression model
3733        let cols = if self.n_class <= 2 {
3734            1
3735        } else {
3736            match shape {
3737                DecisionShape::Ovo => self.n_class * (self.n_class - 1) / 2,
3738                DecisionShape::Ovr => self.n_class,
3739            }
3740        };
3741        check_dense(
3742            "decision_function",
3743            "decision_values",
3744            Layout::ColMajor,
3745            n_samples,
3746            cols,
3747            ldd,
3748            decision_values.len(),
3749        )?;
3750        let status = unsafe {
3751            sys::da_svm_decision_function_d(
3752                self.handle.raw,
3753                n_samples as sys::da_int,
3754                n_features as sys::da_int,
3755                x_test.as_ptr(),
3756                n_samples as sys::da_int,
3757                shape.raw(),
3758                decision_values.as_mut_ptr(),
3759                ldd as sys::da_int,
3760            )
3761        };
3762        check_status("data-analytics", status)
3763    }
3764}
3765
3766impl std::fmt::Debug for Svm {
3767    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3768        f.debug_struct("Svm")
3769            .field("kind", &self.kind)
3770            .field("handle", &self.handle)
3771            .finish()
3772    }
3773}
3774
3775#[cfg(test)]
3776mod tests {
3777    use super::*;
3778
3779    #[test]
3780    fn column_means_2x3() {
3781        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0];
3782        let mut out = [0.0_f64; 3];
3783        mean(Axis::Col, 2, 3, &x, &mut out).unwrap();
3784        assert!((out[0] - 2.5).abs() < 1e-12);
3785        assert!((out[1] - 3.5).abs() < 1e-12);
3786        assert!((out[2] - 4.5).abs() < 1e-12);
3787    }
3788
3789    #[test]
3790    fn row_means_2x3() {
3791        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0];
3792        let mut out = [0.0_f64; 2];
3793        mean(Axis::Row, 2, 3, &x, &mut out).unwrap();
3794        assert!((out[0] - 2.0).abs() < 1e-12);
3795        assert!((out[1] - 5.0).abs() < 1e-12);
3796    }
3797
3798    #[test]
3799    fn variance_dof_conventions() {
3800        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
3801        let mut mu = [0.0_f64; 1];
3802        let mut var = [0.0_f64; 1];
3803
3804        variance(Axis::All, 1, 5, &x, -1, &mut mu, &mut var).unwrap();
3805        assert!((mu[0] - 3.0).abs() < 1e-12);
3806        assert!((var[0] - 2.0).abs() < 1e-12, "n-divisor var = {}", var[0]);
3807
3808        variance(Axis::All, 1, 5, &x, 0, &mut mu, &mut var).unwrap();
3809        assert!(
3810            (var[0] - 2.5).abs() < 1e-12,
3811            "(n-1)-divisor var = {}",
3812            var[0]
3813        );
3814
3815        variance(Axis::All, 1, 5, &x, 2, &mut mu, &mut var).unwrap();
3816        assert!(
3817            (var[0] - 5.0).abs() < 1e-12,
3818            "literal-divisor var = {}",
3819            var[0]
3820        );
3821    }
3822
3823    #[test]
3824    fn dim_mismatch_is_error() {
3825        let x = [1.0_f64; 4];
3826        let mut out = [0.0_f64; 3];
3827        let err = mean(Axis::Col, 2, 3, &x, &mut out).unwrap_err();
3828        matches!(err, Error::InvalidArgument(_));
3829    }
3830
3831    #[test]
3832    fn handle_init_destroy() {
3833        // Smoke test: handle creation + drop on each algorithm kind.
3834        let _h1 = Handle::new_double(HandleKind::Kmeans).unwrap();
3835        let _h2 = Handle::new_double(HandleKind::Pca).unwrap();
3836        let _h3 = Handle::new_single(HandleKind::Linmod).unwrap();
3837    }
3838
3839    #[test]
3840    fn pca_two_components() {
3841        // 4 points in 3-D forming a clear 2-D plane: x and y vary,
3842        // z is small noise.
3843        // Stored column-major (column = feature).
3844        let data: Vec<f64> = vec![
3845            // feature 0 (x): values 1, 2, 3, 4
3846            1.0, 2.0, 3.0, 4.0, // feature 1 (y): values 4, 3, 2, 1
3847            4.0, 3.0, 2.0, 1.0, // feature 2 (z): tiny noise
3848            0.01, 0.02, 0.01, 0.02,
3849        ];
3850        let mut pca = Pca::new(2).unwrap();
3851        pca.fit(4, 3, &data).unwrap();
3852
3853        let mut transformed = vec![0.0_f64; 4 * 2];
3854        pca.transform(4, 3, &data, 2, &mut transformed).unwrap();
3855        // First two PCs should capture nearly all the variance — the
3856        // transformed values should be non-trivial (not all zero).
3857        let nonzero = transformed.iter().any(|&v| v.abs() > 1e-6);
3858        assert!(nonzero, "PCA-transformed coordinates were all zero");
3859    }
3860
3861    #[test]
3862    fn knn_two_class_separation() {
3863        // Two clusters in 2-D (column-major): label 0 around (0,0),
3864        // label 1 around (10,10).
3865        let x_train: Vec<f64> = vec![
3866            // feature 0
3867            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, // feature 1
3868            0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
3869        ];
3870        let y_train = vec![0_i32, 0, 0, 1, 1, 1];
3871        let mut knn = KNearestNeighbours::new().unwrap();
3872        knn.fit(6, 2, &x_train, &y_train).unwrap();
3873
3874        // A query point near (0, 0) → label 0; near (10, 10) → label 1.
3875        let x_test = vec![
3876            0.05, 9.95, // feature 0
3877            0.05, 10.05, // feature 1
3878        ];
3879        let mut labels = vec![0_i32; 2];
3880        knn.predict(2, 2, &x_test, &mut labels).unwrap();
3881        assert_eq!(labels[0], 0);
3882        assert_eq!(labels[1], 1);
3883    }
3884
3885    #[test]
3886    fn decision_tree_two_class_separation() {
3887        // Same separable two-class setup as the KNN test.
3888        let x_train: Vec<f64> = vec![
3889            // feature 0
3890            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, // feature 1
3891            0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
3892        ];
3893        let y_train = vec![0_i32, 0, 0, 1, 1, 1];
3894        let mut tree = DecisionTree::new().unwrap();
3895        tree.fit(6, 2, 2, &x_train, &y_train).unwrap();
3896
3897        let x_test = vec![0.05, 9.95, 0.05, 10.05];
3898        let mut labels = vec![0_i32; 2];
3899        tree.predict(2, 2, &x_test, &mut labels).unwrap();
3900        assert_eq!(labels[0], 0);
3901        assert_eq!(labels[1], 1);
3902
3903        // Score on the training set should be 1.0 for this separable problem.
3904        let acc = tree.score(6, 2, &x_train, &y_train).unwrap();
3905        assert!((acc - 1.0).abs() < 1e-9, "score = {acc}");
3906    }
3907
3908    #[test]
3909    fn decision_forest_two_class_separation() {
3910        let x_train: Vec<f64> = vec![
3911            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, 0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
3912        ];
3913        let y_train = vec![0_i32, 0, 0, 1, 1, 1];
3914        let mut forest = DecisionForest::new().unwrap();
3915        forest.fit(6, 2, 2, &x_train, &y_train).unwrap();
3916
3917        let x_test = vec![0.05, 9.95, 0.05, 10.05];
3918        let mut labels = vec![0_i32; 2];
3919        forest.predict(2, 2, &x_test, &mut labels).unwrap();
3920        assert_eq!(labels[0], 0);
3921        assert_eq!(labels[1], 1);
3922
3923        let acc = forest.score(6, 2, &x_train, &y_train).unwrap();
3924        assert!((acc - 1.0).abs() < 1e-9, "score = {acc}");
3925    }
3926
3927    #[test]
3928    fn datastore_init_destroy_and_options() {
3929        let mut store = Datastore::new().unwrap();
3930        // Setting a few standard options should succeed even on an
3931        // empty store.
3932        store.set_int_option("use header row", 1).unwrap();
3933        store.set_int_option("whitespace delimiter", 1).unwrap();
3934        store.set_string_option("comment", "#").unwrap();
3935        // dims() should report (0, 0) before any data is loaded.
3936        let (r, c) = store.dims().unwrap();
3937        assert_eq!((r, c), (0, 0));
3938    }
3939
3940    #[test]
3941    fn datastore_round_trip_through_temp_csv() {
3942        // Write a minimal numeric CSV to a tempfile, load it via the
3943        // datastore, select all columns, and extract.
3944        use std::io::Write;
3945        let mut path = std::env::temp_dir();
3946        path.push(format!("aocl_da_csv_{}.csv", std::process::id()));
3947        {
3948            let mut f = std::fs::File::create(&path).unwrap();
3949            // 3 rows × 2 cols; no header.
3950            writeln!(f, "1.0,2.0").unwrap();
3951            writeln!(f, "3.0,4.0").unwrap();
3952            writeln!(f, "5.0,6.0").unwrap();
3953        }
3954
3955        let mut store = Datastore::new().unwrap();
3956        store.load_csv(path.to_str().unwrap()).unwrap();
3957        let (r, c) = store.dims().unwrap();
3958        assert_eq!((r, c), (3, 2));
3959
3960        store.select_columns("all", 0, 1).unwrap();
3961        let mut buf = vec![0.0_f64; 6];
3962        // Column-major layout, lddata = n_rows.
3963        store
3964            .extract_f64("all", Layout::ColMajor, &mut buf, 3)
3965            .unwrap();
3966        // Column 0 = [1, 3, 5]; column 1 = [2, 4, 6].
3967        assert!((buf[0] - 1.0).abs() < 1e-12);
3968        assert!((buf[1] - 3.0).abs() < 1e-12);
3969        assert!((buf[2] - 5.0).abs() < 1e-12);
3970        assert!((buf[3] - 2.0).abs() < 1e-12);
3971        assert!((buf[4] - 4.0).abs() < 1e-12);
3972        assert!((buf[5] - 6.0).abs() < 1e-12);
3973
3974        let _ = std::fs::remove_file(&path);
3975    }
3976
3977    /// Red-first, SAFE code only: several threads each build and fit their own `Nlls` through the safe API. RALFit in
3978    /// `aocl-da.dll` is not safe to run concurrently (AOCL 6.0.68, Windows: the process died with an access violation
3979    /// before the wrapper serialised the NLLS library calls). Each thread must recover its own parameters.
3980    #[test]
3981    fn concurrent_nlls_fits_through_the_safe_api_do_not_crash() {
3982        let threads: Vec<_> = (0..6)
3983            .map(|k| {
3984                std::thread::spawn(move || {
3985                    for rep in 0..15 {
3986                        let t: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0];
3987                        let (a, b) = (1.0 + k as f64 * 0.5, 0.2 + 0.05 * rep as f64);
3988                        let y: Vec<f64> = t.iter().map(|&ti| a * (-b * ti).exp()).collect();
3989                        let resfun = move |x: &[f64], res: &mut [f64]| -> i32 {
3990                            for i in 0..res.len() {
3991                                res[i] = x[0] * (-x[1] * t[i]).exp() - y[i];
3992                            }
3993                            0
3994                        };
3995                        let mut m = Nlls::new(2, 5, resfun).unwrap();
3996                        let mut coef = vec![1.0_f64, 1.0_f64];
3997                        m.fit(&mut coef).unwrap();
3998                        assert!(
3999                            (coef[0] - a).abs() < 1e-3 && (coef[1] - b).abs() < 1e-3,
4000                            "thread {k} rep {rep}: {coef:?} vs ({a}, {b})"
4001                        );
4002                    }
4003                })
4004            })
4005            .collect();
4006        for h in threads {
4007            h.join().unwrap();
4008        }
4009    }
4010
4011    #[test]
4012    fn nlls_fits_exponential_decay() {
4013        // Fit y(t) = a · exp(-b · t) to noiseless data with a=2, b=0.3.
4014        // 5 sample points; residuals = predictions - observed.
4015        let t: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0];
4016        let true_a = 2.0_f64;
4017        let true_b = 0.3_f64;
4018        let y: Vec<f64> = t.iter().map(|&ti| true_a * (-true_b * ti).exp()).collect();
4019
4020        // Closure captures t and y by reference. resfun computes
4021        // r_i(x) = a · exp(-b · t_i) - y_i, where x = [a, b].
4022        let n_coef = 2;
4023        let n_res = t.len();
4024        let resfun = |x: &[f64], res: &mut [f64]| -> i32 {
4025            let a = x[0];
4026            let b = x[1];
4027            for i in 0..res.len() {
4028                res[i] = a * (-b * t[i]).exp() - y[i];
4029            }
4030            0
4031        };
4032
4033        let mut model = Nlls::new(n_coef, n_res, resfun).unwrap();
4034        // Start far from the truth to give the optimiser real work.
4035        let mut coef = vec![1.0_f64, 1.0_f64];
4036        model.fit(&mut coef).unwrap();
4037
4038        // Should recover the true parameters within a tight tolerance.
4039        assert!((coef[0] - true_a).abs() < 1e-4, "a = {}", coef[0]);
4040        assert!((coef[1] - true_b).abs() < 1e-4, "b = {}", coef[1]);
4041
4042        // Solver info should report nonzero iterations.
4043        let rinfo = model.info().unwrap();
4044        assert!(!rinfo.is_empty());
4045        // info[2] is iter count per the C header; should be > 0.
4046        assert!(rinfo[2] > 0.0, "iterations = {}", rinfo[2]);
4047    }
4048
4049    #[test]
4050    fn linear_kernel_self_gram() {
4051        // X = [[1, 0], [0, 1], [1, 1]] row-major; Gram = X·Xᵀ
4052        // = [[1, 0, 1], [0, 1, 1], [1, 1, 2]]
4053        let x = [1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4054        let mut d = [0.0_f64; 9];
4055        linear_kernel::<f64>(3, 0, 2, &x, None, &mut d).unwrap();
4056        let want = [1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0];
4057        for (got, w) in d.iter().zip(want.iter()) {
4058            assert!((got - w).abs() < 1e-12, "got {got}, want {w}");
4059        }
4060    }
4061
4062    #[test]
4063    fn rbf_kernel_diagonal_is_one() {
4064        // RBF kernel of any vector with itself is exp(0) = 1.
4065        // Two-point set; check the diagonal entries.
4066        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]; // 2 rows × 3 cols
4067        let mut d = [0.0_f64; 4];
4068        rbf_kernel::<f64>(2, 0, 3, &x, None, &mut d, 0.5).unwrap();
4069        // d[0] (= K(x0, x0)) and d[3] (= K(x1, x1)) should be 1.
4070        assert!((d[0] - 1.0).abs() < 1e-12, "K(x0,x0) = {}", d[0]);
4071        assert!((d[3] - 1.0).abs() < 1e-12, "K(x1,x1) = {}", d[3]);
4072        // Off-diagonal should be < 1.
4073        assert!(d[1] < 1.0);
4074        assert!(d[2] < 1.0);
4075    }
4076
4077    #[test]
4078    fn pairwise_distances_within_set() {
4079        // Three 2-D points on the corners of a 3-4-5 right triangle:
4080        // p0 = (0, 0); p1 = (3, 0); p2 = (0, 4)
4081        // Row-major 3×2 matrix.
4082        let x = [0.0_f64, 0.0, 3.0, 0.0, 0.0, 4.0];
4083        let mut d = [0.0_f64; 9];
4084        pairwise_distances::<f64>(3, 0, 2, &x, None, &mut d, 2.0, Metric::Euclidean).unwrap();
4085        // d is 3×3 row-major; diagonal = 0, off-diagonals are 3, 4, 5.
4086        assert!(d[0].abs() < 1e-12);
4087        assert!((d[1] - 3.0).abs() < 1e-9, "d[0,1] = {}", d[1]);
4088        assert!((d[2] - 4.0).abs() < 1e-9, "d[0,2] = {}", d[2]);
4089        assert!((d[3] - 3.0).abs() < 1e-9);
4090        assert!(d[4].abs() < 1e-12);
4091        assert!((d[5] - 5.0).abs() < 1e-9, "d[1,2] = {}", d[5]);
4092    }
4093
4094    #[test]
4095    fn quantile_median_of_1_to_5() {
4096        // Row-major 1×5 row vector; median (q=0.5) should be 3.
4097        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
4098        let mut q = [0.0_f64; 1];
4099        quantile(Axis::All, 1, 5, &x, 0.5, &mut q, QuantileType::Type7).unwrap();
4100        assert!((q[0] - 3.0).abs() < 1e-12, "median = {}", q[0]);
4101    }
4102
4103    #[test]
4104    fn five_point_summary_works() {
4105        // 1×5 row vector — five-number summary should give 1, ?, 3, ?, 5.
4106        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
4107        let mut min = [0.0_f64; 1];
4108        let mut lower = [0.0_f64; 1];
4109        let mut med = [0.0_f64; 1];
4110        let mut upper = [0.0_f64; 1];
4111        let mut max = [0.0_f64; 1];
4112        five_point_summary(
4113            Axis::All,
4114            1,
4115            5,
4116            &x,
4117            &mut min,
4118            &mut lower,
4119            &mut med,
4120            &mut upper,
4121            &mut max,
4122        )
4123        .unwrap();
4124        assert!((min[0] - 1.0).abs() < 1e-12);
4125        assert!((max[0] - 5.0).abs() < 1e-12);
4126        assert!((med[0] - 3.0).abs() < 1e-12);
4127        // Hinges should sit between min and median, median and max.
4128        assert!(lower[0] >= min[0] && lower[0] <= med[0]);
4129        assert!(upper[0] >= med[0] && upper[0] <= max[0]);
4130    }
4131
4132    /// Rows (1,2), (2,1), (3,4), (4,3): both column means are 2.5, so with the (n-1) divisor (`dof = 0`) both variances
4133    /// are 5/3 and the covariance is 1. If the data were wrongly treated as already centred (AOCL 5.3's
4134    /// `assume_centered = 1`) the diagonal would be 10 and the off-diagonal 11/3 instead.
4135    #[test]
4136    fn covariance_matrix_subtracts_column_means() {
4137        let x = [1.0_f64, 2.0, 2.0, 1.0, 3.0, 4.0, 4.0, 3.0];
4138        let mut cov = [0.0_f64; 4];
4139        covariance_matrix(4, 2, &x, 0, &mut cov).unwrap();
4140        let want = [5.0 / 3.0, 1.0, 1.0, 5.0 / 3.0];
4141        for (g, w) in cov.iter().zip(want) {
4142            assert!((g - w).abs() < 1e-12, "cov = {cov:?}, want {want:?}");
4143        }
4144    }
4145
4146    #[test]
4147    fn correlation_matrix_identity_for_perfectly_correlated() {
4148        // Two perfectly correlated columns: y = 2*x + 1. Correlation
4149        // matrix is the 2x2 all-ones matrix.
4150        // Row-major: 4 rows, 2 columns.
4151        let x = [1.0_f64, 3.0, 2.0, 5.0, 3.0, 7.0, 4.0, 9.0];
4152        let mut corr = [0.0_f64; 4];
4153        correlation_matrix(4, 2, &x, &mut corr).unwrap();
4154        for v in &corr {
4155            assert!((v - 1.0).abs() < 1e-9, "off-diagonal correlation = {}", v);
4156        }
4157    }
4158
4159    #[test]
4160    fn skewness_kurtosis_normal_data_near_zero() {
4161        // Symmetric data → skewness ≈ 0; mesokurtic ≈ 0 (Fisher).
4162        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0]; // 1×5 row vector
4163        let mut mu = [0.0_f64; 1];
4164        let mut var = [0.0_f64; 1];
4165        let mut skew = [0.0_f64; 1];
4166        skewness(Axis::All, 1, 5, &x, &mut mu, &mut var, &mut skew).unwrap();
4167        assert!((mu[0] - 3.0).abs() < 1e-12);
4168        assert!(skew[0].abs() < 1e-9, "skewness = {}", skew[0]);
4169
4170        let mut kurt = [0.0_f64; 1];
4171        kurtosis(Axis::All, 1, 5, &x, &mut mu, &mut var, &mut kurt).unwrap();
4172        // Uniform discrete sample like 1..5 has Fisher kurtosis = -1.3.
4173        assert!(kurt[0] < 0.0, "kurtosis = {}", kurt[0]);
4174    }
4175
4176    #[test]
4177    fn svm_svc_two_class_separation() {
4178        // Same separable two-class setup; SVM uses f64 labels (class
4179        // indices stored as floats).
4180        let x_train: Vec<f64> = vec![
4181            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, 0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
4182        ];
4183        let y_train = vec![0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4184        let mut svm = Svm::new_svc().unwrap();
4185        svm.fit(6, 2, &x_train, &y_train).unwrap();
4186
4187        let x_test = vec![0.05, 9.95, 0.05, 10.05];
4188        let mut predictions = vec![0.0_f64; 2];
4189        svm.predict(2, 2, &x_test, &mut predictions).unwrap();
4190        assert!(
4191            (predictions[0] - 0.0).abs() < 1e-9,
4192            "pred[0] = {}",
4193            predictions[0]
4194        );
4195        assert!(
4196            (predictions[1] - 1.0).abs() < 1e-9,
4197            "pred[1] = {}",
4198            predictions[1]
4199        );
4200
4201        let acc = svm.score(6, 2, &x_train, &y_train).unwrap();
4202        assert!((acc - 1.0).abs() < 1e-9, "score = {acc}");
4203    }
4204
4205    #[test]
4206    fn dbscan_two_clusters() {
4207        // Two well-separated clusters; should yield n_clusters = 2 and
4208        // each cluster's samples sharing a positive label.
4209        let data: Vec<f64> = vec![
4210            // feature 0 (column 0): cluster A near 0, cluster B near 10
4211            0.0, 0.1, 0.2, 0.0, 0.1, 10.0, 10.1, 10.0, 10.2, 10.1, // feature 1 (column 1)
4212            0.0, 0.1, 0.0, 0.2, 0.1, 10.0, 10.1, 10.2, 10.0, 10.1,
4213        ];
4214        let mut db = Dbscan::new().unwrap();
4215        // Set min_samples small so a 5-point cluster qualifies; eps the
4216        // default (which is ~0.5 in AOCL) is not enough so widen it.
4217        // We use the underlying real-valued setter directly.
4218        let cs = std::ffi::CString::new("eps").unwrap();
4219        let status =
4220            unsafe { sys::da_options_set_real_d(db.handle_mut().as_raw(), cs.as_ptr(), 1.0) };
4221        assert_eq!(status, sys::da_status__da_status_success);
4222        db.handle_mut().set_int_option("min samples", 3).unwrap();
4223        db.fit(10, 2, &data).unwrap();
4224        assert_eq!(db.n_clusters().unwrap(), 2);
4225        let labels = db.labels().unwrap();
4226        // First five samples share a label, last five share another.
4227        assert_eq!(labels[0], labels[1]);
4228        assert_eq!(labels[1], labels[2]);
4229        assert_eq!(labels[5], labels[6]);
4230        assert_eq!(labels[6], labels[9]);
4231        assert_ne!(labels[0], labels[5]);
4232        assert!(db.n_core_samples().unwrap() > 0);
4233    }
4234
4235    #[test]
4236    fn linmod_mse_recovers_linear_relationship() {
4237        // y = 2 * x0 + 3 * x1 + small intercept; one feature varies with
4238        // each axis. Column-major: feature 0 first, then feature 1.
4239        // Use 5 samples to give the solver something to work with.
4240        let x: Vec<f64> = vec![
4241            // feature 0
4242            1.0, 2.0, 3.0, 4.0, 5.0, // feature 1
4243            5.0, 4.0, 3.0, 2.0, 1.0,
4244        ];
4245        // y = 2·x0 + 3·x1 (no noise)
4246        let y: Vec<f64> = vec![17.0, 16.0, 15.0, 14.0, 13.0];
4247        let mut model = Linmod::new_mse().unwrap();
4248        model.fit(5, 2, &x, &y).unwrap();
4249        let coefs = model.coefficients().unwrap();
4250        assert!(!coefs.is_empty(), "fitted coefficients vector was empty");
4251        // The first two entries should approximate the true coefficients.
4252        // AOCL may report them with small floating-point noise.
4253        assert!((coefs[0] - 2.0).abs() < 1e-6, "coef[0] = {}", coefs[0]);
4254        assert!((coefs[1] - 3.0).abs() < 1e-6, "coef[1] = {}", coefs[1]);
4255
4256        // Predict on the same samples — should reproduce y nearly exactly.
4257        let mut pred = vec![0.0_f64; 5];
4258        model.predict(5, 2, &x, &mut pred).unwrap();
4259        for (got, want) in pred.iter().zip(y.iter()) {
4260            assert!((got - want).abs() < 1e-6, "predict {} vs {}", got, want);
4261        }
4262
4263        // evaluate() produces a loss; the loss for an exact fit is small
4264        // (zero up to floating-point noise).
4265        let mut pred2 = vec![0.0_f64; 5];
4266        let loss = model.evaluate(5, 2, &x, &y, &mut pred2).unwrap();
4267        assert!(loss.abs() < 1e-6, "exact-fit loss = {}", loss);
4268    }
4269
4270    #[test]
4271    fn kmeans_two_clusters() {
4272        // Two well-separated clusters: rows 0..=2 near (0, 0); rows
4273        // 3..=5 near (10, 10). Stored column-major: feature 0 first,
4274        // then feature 1.
4275        let data: Vec<f64> = vec![
4276            // feature 0 (column 0)
4277            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, // feature 1 (column 1)
4278            0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
4279        ];
4280        let mut km = KMeans::new(2).unwrap();
4281        km.fit(6, 2, &data).unwrap();
4282
4283        // Predict on the same six samples; rows 0..=2 should share a
4284        // label, rows 3..=5 the other.
4285        let mut labels = vec![0_i32; 6];
4286        km.predict(6, 2, &data, &mut labels).unwrap();
4287        assert_eq!(labels[0], labels[1]);
4288        assert_eq!(labels[1], labels[2]);
4289        assert_eq!(labels[3], labels[4]);
4290        assert_eq!(labels[4], labels[5]);
4291        assert_ne!(labels[0], labels[3]);
4292    }
4293
4294    // ---- reference helpers: naive formulas, independent of AOCL ----
4295
4296    fn near(a: f64, b: f64, tol: f64, what: &str) {
4297        assert!(
4298            (a - b).abs() <= tol * (1.0 + b.abs()),
4299            "{what}: got {a}, want {b}"
4300        );
4301    }
4302
4303    /// Column `j` (axis = Col) or row `i` (axis = Row) of a row-major `r x c` matrix.
4304    fn slices(x: &[f64], r: usize, c: usize, axis: Axis) -> Vec<Vec<f64>> {
4305        match axis {
4306            Axis::Col => (0..c)
4307                .map(|j| (0..r).map(|i| x[i * c + j]).collect())
4308                .collect(),
4309            Axis::Row => (0..r).map(|i| x[i * c..(i + 1) * c].to_vec()).collect(),
4310            _ => unreachable!(),
4311        }
4312    }
4313
4314    const X23: [f64; 6] = [1.0, 2.0, 4.0, 4.0, 8.0, 16.0]; // row-major 2 x 3, all positive
4315
4316    #[test]
4317    fn geometric_mean_matches_exp_mean_log_f64_and_f32() {
4318        for axis in [Axis::Col, Axis::Row] {
4319            let want: Vec<f64> = slices(&X23, 2, 3, axis)
4320                .iter()
4321                .map(|v| (v.iter().map(|x| x.ln()).sum::<f64>() / v.len() as f64).exp())
4322                .collect();
4323            let mut out = vec![0.0_f64; want.len()];
4324            geometric_mean(axis, 2, 3, &X23, &mut out).unwrap();
4325            for (g, w) in out.iter().zip(&want) {
4326                near(*g, *w, 1e-12, "f64 geometric mean");
4327            }
4328            let x32: Vec<f32> = X23.iter().map(|&v| v as f32).collect();
4329            let mut out32 = vec![0.0_f32; want.len()];
4330            geometric_mean(axis, 2, 3, &x32, &mut out32).unwrap();
4331            for (g, w) in out32.iter().zip(&want) {
4332                near(*g as f64, *w, 1e-5, "f32 geometric mean");
4333            }
4334        }
4335        // Closed form: columns of [[1,2,4],[4,8,16]] have geometric means sqrt(4)=2, sqrt(16)=4, sqrt(64)=8.
4336        let mut out = [0.0_f64; 3];
4337        geometric_mean(Axis::Col, 2, 3, &X23, &mut out).unwrap();
4338        for (g, w) in out.iter().zip([2.0, 4.0, 8.0]) {
4339            near(*g, w, 1e-12, "closed-form geometric mean");
4340        }
4341    }
4342
4343    #[test]
4344    fn harmonic_mean_matches_n_over_sum_of_reciprocals_f64_and_f32() {
4345        for axis in [Axis::Col, Axis::Row] {
4346            let want: Vec<f64> = slices(&X23, 2, 3, axis)
4347                .iter()
4348                .map(|v| v.len() as f64 / v.iter().map(|x| 1.0 / x).sum::<f64>())
4349                .collect();
4350            let mut out = vec![0.0_f64; want.len()];
4351            harmonic_mean(axis, 2, 3, &X23, &mut out).unwrap();
4352            for (g, w) in out.iter().zip(&want) {
4353                near(*g, *w, 1e-12, "f64 harmonic mean");
4354            }
4355            let x32: Vec<f32> = X23.iter().map(|&v| v as f32).collect();
4356            let mut out32 = vec![0.0_f32; want.len()];
4357            harmonic_mean(axis, 2, 3, &x32, &mut out32).unwrap();
4358            for (g, w) in out32.iter().zip(&want) {
4359                near(*g as f64, *w, 1e-5, "f32 harmonic mean");
4360            }
4361        }
4362        // Closed form: harmonic mean of {1, 4} = 2 / (1 + 1/4) = 1.6.
4363        let mut out = [0.0_f64; 3];
4364        harmonic_mean(Axis::Col, 2, 3, &X23, &mut out).unwrap();
4365        near(out[0], 1.6, 1e-12, "harmonic mean of column 0");
4366    }
4367
4368    #[test]
4369    fn moment_matches_central_moment_definition_f64_and_f32() {
4370        let x = [
4371            1.0_f64, 2.0, 4.0, 8.0, 3.0, 5.0, 7.0, 11.0, 6.0, 9.0, 10.0, 14.0,
4372        ]; // 4 x 3
4373        for axis in [Axis::Col, Axis::Row] {
4374            let sl = slices(&x, 4, 3, axis);
4375            for k in [2_i64, 3] {
4376                let means: Vec<f64> = sl
4377                    .iter()
4378                    .map(|v| v.iter().sum::<f64>() / v.len() as f64)
4379                    .collect();
4380                let want: Vec<f64> = sl
4381                    .iter()
4382                    .zip(&means)
4383                    .map(|(v, m)| {
4384                        v.iter().map(|x| (x - m).powi(k as i32)).sum::<f64>() / v.len() as f64
4385                    })
4386                    .collect();
4387                let mut mean_out = vec![0.0_f64; sl.len()];
4388                let mut mom = vec![0.0_f64; sl.len()];
4389                moment(axis, 4, 3, &x, k, false, &mut mean_out, &mut mom).unwrap();
4390                for j in 0..sl.len() {
4391                    near(mean_out[j], means[j], 1e-12, "moment: mean output");
4392                    near(mom[j], want[j], 1e-10, "f64 central moment");
4393                }
4394                // Precomputed means supplied: same result.
4395                let mut mom2 = vec![0.0_f64; sl.len()];
4396                let mut means_in = means.clone();
4397                moment(axis, 4, 3, &x, k, true, &mut means_in, &mut mom2).unwrap();
4398                for j in 0..sl.len() {
4399                    near(
4400                        mom2[j],
4401                        want[j],
4402                        1e-10,
4403                        "f64 central moment, precomputed mean",
4404                    );
4405                }
4406                let x32: Vec<f32> = x.iter().map(|&v| v as f32).collect();
4407                let mut m32 = vec![0.0_f32; sl.len()];
4408                let mut mom32 = vec![0.0_f32; sl.len()];
4409                moment(axis, 4, 3, &x32, k, false, &mut m32, &mut mom32).unwrap();
4410                for j in 0..sl.len() {
4411                    near(mom32[j] as f64, want[j], 1e-4, "f32 central moment");
4412                }
4413            }
4414        }
4415    }
4416
4417    #[test]
4418    fn moment_rejects_short_output() {
4419        let mut m = [0.0_f64; 1];
4420        let mut o = [0.0_f64; 1];
4421        assert!(moment(Axis::Col, 2, 3, &X23, 2, false, &mut m, &mut o).is_err());
4422    }
4423
4424    fn dot(a: &[f64], b: &[f64]) -> f64 {
4425        a.iter().zip(b).map(|(x, y)| x * y).sum()
4426    }
4427
4428    #[test]
4429    fn polynomial_and_sigmoid_kernels_match_definitions_f64_and_f32() {
4430        let x = [1.0_f64, 0.5, -1.0, 2.0, 0.0, 1.5]; // 3 x 2 row-major
4431        let y = [0.5_f64, -0.5, 1.0, 1.0]; // 2 x 2
4432        let (gamma, coef0, degree) = (0.5_f64, 1.0_f64, 3_i64);
4433        let rows = |m: &[f64], n: usize| -> Vec<Vec<f64>> {
4434            (0..n).map(|i| m[i * 2..i * 2 + 2].to_vec()).collect()
4435        };
4436        let (xr, yr) = (rows(&x, 3), rows(&y, 2));
4437        // Cross kernel (3 x 2) and self kernel (3 x 3).
4438        for with_y in [true, false] {
4439            let (n, other): (usize, &Vec<Vec<f64>>) = if with_y { (2, &yr) } else { (3, &xr) };
4440            let ys: Option<&[f64]> = if with_y { Some(&y) } else { None };
4441            let mut pd = vec![0.0_f64; 3 * n];
4442            polynomial_kernel(3, n, 2, &x, ys, &mut pd, gamma, degree, coef0).unwrap();
4443            let mut sg = vec![0.0_f64; 3 * n];
4444            sigmoid_kernel(3, n, 2, &x, ys, &mut sg, gamma, coef0).unwrap();
4445            let x32: Vec<f32> = x.iter().map(|&v| v as f32).collect();
4446            let y32: Vec<f32> = y.iter().map(|&v| v as f32).collect();
4447            let ys32: Option<&[f32]> = if with_y { Some(&y32) } else { None };
4448            let mut pd32 = vec![0.0_f32; 3 * n];
4449            polynomial_kernel(
4450                3,
4451                n,
4452                2,
4453                &x32,
4454                ys32,
4455                &mut pd32,
4456                gamma as f32,
4457                degree,
4458                coef0 as f32,
4459            )
4460            .unwrap();
4461            let mut sg32 = vec![0.0_f32; 3 * n];
4462            sigmoid_kernel(3, n, 2, &x32, ys32, &mut sg32, gamma as f32, coef0 as f32).unwrap();
4463            for i in 0..3 {
4464                for j in 0..n {
4465                    let d = dot(&xr[i], &other[j]);
4466                    let wp = (gamma * d + coef0).powi(degree as i32);
4467                    let ws = (gamma * d + coef0).tanh();
4468                    near(pd[i * n + j], wp, 1e-12, "polynomial kernel f64");
4469                    near(sg[i * n + j], ws, 1e-12, "sigmoid kernel f64");
4470                    near(pd32[i * n + j] as f64, wp, 1e-4, "polynomial kernel f32");
4471                    near(sg32[i * n + j] as f64, ws, 1e-5, "sigmoid kernel f32");
4472                }
4473            }
4474        }
4475    }
4476
4477    #[test]
4478    fn datastore_n_cols_and_select_rows() {
4479        use std::io::Write;
4480        let mut path = std::env::temp_dir();
4481        path.push(format!("aocl_da_rows_{}.csv", std::process::id()));
4482        {
4483            let mut f = std::fs::File::create(&path).unwrap();
4484            writeln!(f, "1.0,2.0,3.0").unwrap();
4485            writeln!(f, "4.0,5.0,6.0").unwrap();
4486            writeln!(f, "7.0,8.0,9.0").unwrap();
4487            writeln!(f, "10.0,11.0,12.0").unwrap();
4488        }
4489        let mut store = Datastore::new().unwrap();
4490        assert_eq!(store.n_cols().unwrap(), 0); // empty store (control)
4491        store.load_csv(path.to_str().unwrap()).unwrap();
4492        assert_eq!(store.n_cols().unwrap(), 3);
4493        assert_eq!(store.n_rows().unwrap(), 4);
4494        // Rows 1..=2 (zero-based, inclusive): [[4,5,6],[7,8,9]].
4495        store.select_rows("mid", 1, 2).unwrap();
4496        let mut buf = vec![0.0_f64; 6];
4497        store
4498            .extract_f64("mid", Layout::RowMajor, &mut buf, 3)
4499            .unwrap();
4500        assert_eq!(buf, [4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
4501        // Out-of-range selection is an error.
4502        assert!(store.select_rows("bad", 0, 10).is_err());
4503        let _ = std::fs::remove_file(&path);
4504    }
4505
4506    fn decay_data() -> (Vec<f64>, Vec<f64>) {
4507        let t: Vec<f64> = (0..8).map(|i| i as f64 * 0.5).collect();
4508        let y: Vec<f64> = t.iter().map(|&ti| 2.0 * (-0.3 * ti).exp()).collect();
4509        (t, y)
4510    }
4511
4512    #[test]
4513    fn nlls_with_analytic_jacobian_recovers_parameters() {
4514        let (t, y) = decay_data();
4515        let (t2, y2) = (t.clone(), y.clone());
4516        let model = Nlls::new(2, t.len(), move |x: &[f64], r: &mut [f64]| {
4517            for i in 0..r.len() {
4518                r[i] = x[0] * (-x[1] * t2[i]).exp() - y2[i];
4519            }
4520            0
4521        })
4522        .unwrap();
4523        let t3 = t.clone();
4524        let jac_calls = std::cell::Cell::new(0usize);
4525        let mut model = model
4526            .with_jacobian(|x: &[f64], j: &mut [f64]| {
4527                jac_calls.set(jac_calls.get() + 1);
4528                // Row-major n_res x n_coef: d r_i / d a and d r_i / d b.
4529                for i in 0..t3.len() {
4530                    let e = (-x[1] * t3[i]).exp();
4531                    j[i * 2] = e;
4532                    j[i * 2 + 1] = -x[0] * t3[i] * e;
4533                }
4534                0
4535            })
4536            .unwrap();
4537        let mut coef = vec![1.0_f64, 1.0];
4538        model.fit(&mut coef).unwrap();
4539        near(coef[0], 2.0, 1e-5, "a");
4540        near(coef[1], 0.3, 1e-5, "b");
4541        drop(model);
4542        assert!(
4543            jac_calls.get() > 0,
4544            "the analytic Jacobian was never called"
4545        );
4546    }
4547
4548    #[test]
4549    fn nlls_set_bounds_are_respected_and_wide_bounds_do_not_bind() {
4550        let (t, y) = decay_data();
4551        let make = || {
4552            let (t, y) = (t.clone(), y.clone());
4553            Nlls::new(2, 8, move |x: &[f64], r: &mut [f64]| {
4554                for i in 0..r.len() {
4555                    r[i] = x[0] * (-x[1] * t[i]).exp() - y[i];
4556                }
4557                0
4558            })
4559            .unwrap()
4560        };
4561        // Wide bounds around the truth (a = 2, b = 0.3): the unconstrained answer is recovered.
4562        let mut m = make();
4563        m.set_bounds(Some(&mut [0.0, 0.0]), Some(&mut [10.0, 5.0]))
4564            .unwrap();
4565        let mut c = vec![1.0_f64, 1.0];
4566        m.fit(&mut c).unwrap();
4567        near(c[0], 2.0, 1e-4, "a (wide bounds)");
4568        near(c[1], 0.3, 1e-4, "b (wide bounds)");
4569        // Upper bound a <= 1.5 excludes the true a = 2: the fit must stay feasible, sit on the bound, and leave a
4570        // strictly positive residual (the data are exactly generated by a = 2).
4571        let mut m = make();
4572        m.set_bounds(None, Some(&mut [1.5, 5.0])).unwrap();
4573        let mut c = vec![1.0_f64, 1.0];
4574        m.fit(&mut c).unwrap();
4575        assert!(c[0] <= 1.5 + 1e-9, "a = {} violates a <= 1.5", c[0]);
4576        near(c[0], 1.5, 1e-4, "a sits on its upper bound");
4577        let obj: f64 = (0..8)
4578            .map(|i| (c[0] * (-c[1] * t[i]).exp() - y[i]).powi(2))
4579            .sum();
4580        assert!(obj > 1e-4, "constrained objective {obj} should exceed 0");
4581        // Lower bound b >= 0.5 excludes the true b = 0.3.
4582        let mut m = make();
4583        m.set_bounds(Some(&mut [0.0, 0.5]), None).unwrap();
4584        let mut c = vec![1.0_f64, 1.0];
4585        m.fit(&mut c).unwrap();
4586        assert!(c[1] >= 0.5 - 1e-9, "b = {} violates b >= 0.5", c[1]);
4587        // Too-short bound slices are rejected.
4588        let mut m = make();
4589        assert!(m.set_bounds(Some(&mut [0.0]), None).is_err());
4590    }
4591
4592    #[test]
4593    fn nlls_set_weights_tiny_weight_suppresses_an_outlier() {
4594        let (t, mut y) = decay_data();
4595        y[7] += 5.0; // corrupt the last observation
4596        let make = || {
4597            let (t, y) = (t.clone(), y.clone());
4598            Nlls::new(2, 8, move |x: &[f64], r: &mut [f64]| {
4599                for i in 0..r.len() {
4600                    r[i] = x[0] * (-x[1] * t[i]).exp() - y[i];
4601                }
4602                0
4603            })
4604            .unwrap()
4605        };
4606        // Unweighted: the outlier drags the fit away from the truth (control for the weighted case).
4607        let mut m = make();
4608        let mut c = vec![1.0_f64, 1.0];
4609        m.fit(&mut c).unwrap();
4610        assert!(
4611            (c[0] - 2.0).abs() > 1e-2 || (c[1] - 0.3).abs() > 1e-2,
4612            "outlier had no effect: {c:?}"
4613        );
4614        // Weights w_i = sqrt(W_ii): AOCL rejects zero ("must be sufficiently positive"), so the outlier gets 1e-4, which
4615        // shrinks its pull by 10^4 and recovers the true parameters to ~1e-3.
4616        let mut m = make();
4617        let mut w = vec![1.0_f64; 8];
4618        w[7] = 1e-4;
4619        m.set_weights(&mut w).unwrap();
4620        let mut c = vec![1.0_f64, 1.0];
4621        m.fit(&mut c).unwrap();
4622        near(c[0], 2.0, 3e-3, "a (weighted)");
4623        near(c[1], 0.3, 3e-3, "b (weighted)");
4624        assert!(m.set_weights(&mut [1.0; 3]).is_err());
4625    }
4626
4627    /// Red-first (deterministic by repetition): before the fix a fresh handle returned a string read from uninitialised
4628    /// memory about 1 time in 25 (success status, pointer into uninitialised heap). Now a handle that has seen no failure
4629    /// never reaches the library call, so every one of 2000 fresh handles gives `None`.
4630    #[test]
4631    fn last_error_message_on_a_fresh_handle_is_none_every_time() {
4632        for i in 0..2000 {
4633            let h = Handle::new_double(HandleKind::Linmod).unwrap();
4634            assert_eq!(h.last_error_message(), None, "fresh handle #{i}");
4635        }
4636    }
4637
4638    #[test]
4639    fn last_error_message_names_the_rejected_option() {
4640        let mut h = Handle::new_double(HandleKind::Linmod).unwrap();
4641        assert!(h.set_int_option("no such option", 1).is_err());
4642        let msg = h
4643            .last_error_message()
4644            .expect("an error message after a rejected option");
4645        assert!(!msg.is_empty());
4646        assert!(
4647            msg.contains("no such option"),
4648            "message does not name the option: {msg}"
4649        );
4650    }
4651
4652    // Two separable clusters in 2-D, column-major (feature 0 then feature 1): class 0 near (0,0), class 1 near (10,10).
4653    const CL_X: [f64; 12] = [
4654        0.0, 0.1, 0.2, 10.0, 10.1, 10.2, 0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
4655    ];
4656    const CL_Y: [i32; 6] = [0, 0, 0, 1, 1, 1];
4657    const CL_TEST: [f64; 4] = [0.05, 9.95, 0.05, 10.05]; // (0.05,0.05) and (9.95,10.05)
4658
4659    #[test]
4660    fn knn_classes_lists_distinct_labels_whatever_the_buffer_size() {
4661        let mut knn = KNearestNeighbours::new().unwrap();
4662        knn.fit(6, 2, &CL_X, &[7, 7, 7, 3, 3, 3]).unwrap();
4663        // Ascending distinct labels; the return value is the number of classes, not the buffer length.
4664        let mut big = [0_i32; 5];
4665        assert_eq!(knn.classes(&mut big).unwrap(), 2);
4666        assert_eq!(&big[..2], &[3, 7]);
4667        let mut exact = [0_i32; 2];
4668        assert_eq!(knn.classes(&mut exact).unwrap(), 2);
4669        assert_eq!(exact, [3, 7]);
4670    }
4671
4672    #[test]
4673    fn knn_kneighbors_match_brute_force_ranking() {
4674        let mut knn = KNearestNeighbours::new().unwrap();
4675        knn.fit(6, 2, &CL_X, &CL_Y).unwrap();
4676        // Queries (0.04, 0.02) and (10.15, 10.0): no distance ties among the training points.
4677        let q = [0.04, 10.15, 0.02, 10.0];
4678        let k = 3;
4679        let mut ind = vec![0_i32; 2 * k];
4680        let mut dist = vec![0.0_f64; 2 * k];
4681        knn.kneighbors(2, 2, &q, &mut ind, &mut dist, k, true)
4682            .unwrap();
4683        for qi in 0..2 {
4684            let mut ranked: Vec<(f64, i32)> = (0..6)
4685                .map(|i| {
4686                    (
4687                        ((CL_X[i] - q[qi]).powi(2) + (CL_X[6 + i] - q[2 + qi]).powi(2)).sqrt(),
4688                        i as i32,
4689                    )
4690                })
4691                .collect();
4692            ranked.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
4693            for j in 0..k {
4694                // Column-major (n_queries x k): element (query, rank) at rank * n_queries + query.
4695                assert_eq!(ind[j * 2 + qi], ranked[j].1, "query {qi} rank {j}");
4696                near(dist[j * 2 + qi], ranked[j].0, 1e-9, "neighbour distance");
4697            }
4698        }
4699        // Without distances the indices are the same.
4700        let mut ind2 = vec![0_i32; 2 * k];
4701        let mut dist2 = vec![0.0_f64; 2 * k];
4702        knn.kneighbors(2, 2, &q, &mut ind2, &mut dist2, k, false)
4703            .unwrap();
4704        assert_eq!(ind, ind2);
4705    }
4706
4707    #[test]
4708    fn knn_predict_proba_counts_neighbour_classes() {
4709        // Default k = 5 with 3 training points per class: a query always has all 3 of its own cluster plus the 2
4710        // nearest of the other, so P(own class) = 3/5 and P(other) = 2/5. Queries 0 and 1 sit in cluster 0, query 2 in
4711        // cluster 1. The 3 x 2 result is column-major (ldp = n_queries): element (query, class) at class * 3 + query.
4712        let mut knn = KNearestNeighbours::new().unwrap();
4713        knn.fit(6, 2, &CL_X, &CL_Y).unwrap();
4714        let q = [0.05, 0.1, 9.95, 0.05, 0.0, 10.05]; // 3 queries: (0.05,0.05) (0.1,0.0) (9.95,10.05)
4715        let mut proba = vec![0.0_f64; 6];
4716        knn.predict_proba(3, 2, &q, &mut proba).unwrap();
4717        for (g, w) in proba.iter().zip([0.6, 0.6, 0.4, 0.4, 0.4, 0.6]) {
4718            near(*g, w, 1e-9, "knn predict_proba");
4719        }
4720    }
4721
4722    #[test]
4723    fn dbscan_core_sample_indices_exclude_noise() {
4724        // Five points in a tight cluster plus one far outlier: with min samples = 3 and eps = 1 the cluster points
4725        // (indices 0..=4) are core samples, the outlier (index 5) is noise (label -1) and not core.
4726        let data: Vec<f64> = vec![
4727            0.0, 0.1, 0.2, 0.0, 0.1, 50.0, // feature 0
4728            0.0, 0.1, 0.0, 0.2, 0.1, 50.0, // feature 1
4729        ];
4730        let mut db = Dbscan::new().unwrap();
4731        let cs = std::ffi::CString::new("eps").unwrap();
4732        let st = unsafe { sys::da_options_set_real_d(db.handle_mut().as_raw(), cs.as_ptr(), 1.0) };
4733        assert_eq!(st, sys::da_status__da_status_success);
4734        db.handle_mut().set_int_option("min samples", 3).unwrap();
4735        db.fit(6, 2, &data).unwrap();
4736        let mut core = db.core_sample_indices().unwrap();
4737        core.sort();
4738        assert_eq!(core, vec![0, 1, 2, 3, 4]);
4739        assert_eq!(core.len(), db.n_core_samples().unwrap());
4740        let labels = db.labels().unwrap();
4741        assert_eq!(labels[5], -1);
4742        assert!(labels[..5].iter().all(|&l| l == labels[0] && l >= 0));
4743    }
4744
4745    // Four queries (column-major, feature 0 then feature 1): classes 0, 1, 0, 1.
4746    const Q4: [f64; 8] = [0.05, 9.95, 0.2, 10.2, 0.05, 10.05, 0.0, 10.1];
4747
4748    /// Probability outputs are laid out in the handle's storage order (column-major, `ldy >= n_samples`): element
4749    /// (sample `i`, class `c`) is at `c * ldy + i`. (The wrapper's docs say row-major / `ldy >= n_class`: FINDING.)
4750    #[test]
4751    fn tree_and_forest_predict_proba_and_log_proba_on_separable_data() {
4752        let mut tree = DecisionTree::new().unwrap();
4753        tree.fit(6, 2, 2, &CL_X, &CL_Y).unwrap();
4754        let mut forest = DecisionForest::new().unwrap();
4755        forest.fit(6, 2, 2, &CL_X, &CL_Y).unwrap();
4756        let truth = [0usize, 1, 0, 1];
4757        let at = |v: &[f64], i: usize, c: usize| v[c * 4 + i];
4758
4759        let mut tp = vec![0.0_f64; 8];
4760        tree.predict_proba(4, 2, &Q4, &mut tp, 2, 4).unwrap();
4761        for i in 0..4 {
4762            for c in 0..2 {
4763                near(
4764                    at(&tp, i, c),
4765                    if c == truth[i] { 1.0 } else { 0.0 },
4766                    1e-12,
4767                    "tree proba (pure leaves)",
4768                );
4769            }
4770        }
4771        let mut tl = vec![0.0_f64; 8];
4772        tree.predict_log_proba(4, 2, &Q4, &mut tl, 2, 4).unwrap();
4773        for i in 0..4 {
4774            near(
4775                at(&tl, i, truth[i]),
4776                0.0,
4777                1e-12,
4778                "tree log P(true class) = ln 1",
4779            );
4780            assert!(
4781                at(&tl, i, 1 - truth[i]) < -10.0,
4782                "ln 0 must be very negative: {tl:?}"
4783            );
4784        }
4785
4786        let mut fp = vec![0.0_f64; 8];
4787        forest.predict_proba(4, 2, &Q4, &mut fp, 2, 4).unwrap();
4788        for i in 0..4 {
4789            near(
4790                at(&fp, i, 0) + at(&fp, i, 1),
4791                1.0,
4792                1e-9,
4793                "forest probabilities sum to 1",
4794            );
4795            assert!(at(&fp, i, truth[i]) > 0.8, "forest proba {fp:?}");
4796        }
4797        let mut fl = vec![0.0_f64; 8];
4798        forest.predict_log_proba(4, 2, &Q4, &mut fl, 2, 4).unwrap();
4799        // exp(log P) reproduces P wherever P > 0 (the invariant tying the two outputs together).
4800        for (l, p) in fl.iter().zip(&fp) {
4801            if *p > 1e-12 {
4802                near(l.exp(), *p, 1e-9, "forest exp(log_proba) == proba");
4803            }
4804        }
4805    }
4806
4807    #[test]
4808    fn linmod_logistic_separates_two_classes() {
4809        // 1-D, linearly separable at 0: class 0 for x < 0, class 1 for x > 0.
4810        let x = [-2.0_f64, -1.0, -0.5, 0.5, 1.0, 2.0];
4811        let y = [0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4812        let mut m = Linmod::new_logistic().unwrap();
4813        assert_eq!(m.kind(), LinmodKind::Logistic);
4814        m.fit(6, 1, &x, &y).unwrap();
4815        let coefs = m.coefficients().unwrap();
4816        assert!(
4817            coefs[0] > 0.0,
4818            "slope of a positively separated problem must be > 0: {coefs:?}"
4819        );
4820        let mut pred = vec![0.0_f64; 6];
4821        m.predict(6, 1, &x, &mut pred).unwrap();
4822        assert_eq!(pred, y);
4823        // Unseen points on either side of the boundary.
4824        let mut p2 = [0.0_f64; 2];
4825        m.predict(2, 1, &[-3.0, 3.0], &mut p2).unwrap();
4826        assert_eq!(p2, [0.0, 1.0]);
4827    }
4828
4829    fn set_real(svm: &mut Svm, name: &str, v: f64) {
4830        let cs = std::ffi::CString::new(name).unwrap();
4831        let st = unsafe { sys::da_options_set_real_d(svm.handle_mut().as_raw(), cs.as_ptr(), v) };
4832        assert_eq!(st, sys::da_status__da_status_success, "option {name}");
4833    }
4834
4835    #[test]
4836    fn svm_nu_svc_separates_two_classes() {
4837        let y = [0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4838        let mut svm = Svm::new_nu_svc().unwrap();
4839        assert_eq!(svm.kind(), SvmKind::NuSvc);
4840        svm.fit(6, 2, &CL_X, &y).unwrap();
4841        let mut p = [0.0_f64; 2];
4842        svm.predict(2, 2, &CL_TEST, &mut p).unwrap();
4843        assert_eq!(p, [0.0, 1.0]);
4844        near(
4845            svm.score(6, 2, &CL_X, &y).unwrap(),
4846            1.0,
4847            1e-12,
4848            "nu-svc training accuracy",
4849        );
4850    }
4851
4852    #[test]
4853    fn svm_decision_function_sign_separates_classes() {
4854        let y = [0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4855        let mut svm = Svm::new_svc().unwrap();
4856        svm.fit(6, 2, &CL_X, &y).unwrap();
4857        for shape in [DecisionShape::Ovo, DecisionShape::Ovr] {
4858            let mut dv = vec![0.0_f64; 2];
4859            svm.decision_function(2, 2, &CL_TEST, shape, &mut dv, 2)
4860                .unwrap();
4861            // Binary problem (scikit-learn convention): positive value <=> the second class.
4862            assert!(dv[0] < 0.0 && dv[1] > 0.0, "{shape:?}: {dv:?}");
4863        }
4864        // On the training set every class-1 sample scores above every class-0 sample.
4865        let mut dv = vec![0.0_f64; 6];
4866        svm.decision_function(6, 2, &CL_X, DecisionShape::Ovo, &mut dv, 6)
4867            .unwrap();
4868        let max0 = dv[..3].iter().cloned().fold(f64::MIN, f64::max);
4869        let min1 = dv[3..].iter().cloned().fold(f64::MAX, f64::min);
4870        assert!(max0 < min1, "{dv:?}");
4871    }
4872
4873    /// y = 2x + 1 sampled at x = 0..=9: a linear-kernel SVR with a large C must reproduce it within its epsilon tube.
4874    fn regression_data() -> (Vec<f64>, Vec<f64>) {
4875        let x: Vec<f64> = (0..10).map(|i| i as f64).collect();
4876        let y: Vec<f64> = x.iter().map(|&v| 2.0 * v + 1.0).collect();
4877        (x, y)
4878    }
4879
4880    #[test]
4881    fn svm_svr_fits_a_line() {
4882        let (x, y) = regression_data();
4883        let mut svm = Svm::new_svr().unwrap();
4884        assert_eq!(svm.kind(), SvmKind::Svr);
4885        svm.handle_mut()
4886            .set_string_option("kernel", "linear")
4887            .unwrap();
4888        set_real(&mut svm, "C", 1000.0);
4889        set_real(&mut svm, "epsilon", 0.1);
4890        svm.fit(10, 1, &x, &y).unwrap();
4891        let mut p = vec![0.0_f64; 10];
4892        svm.predict(10, 1, &x, &mut p).unwrap();
4893        for (g, w) in p.iter().zip(&y) {
4894            // Epsilon-insensitive loss: training points lie within epsilon (+ solver slack) of the truth.
4895            assert!((g - w).abs() < 0.2, "svr pred {g} vs {w}");
4896        }
4897        assert!(svm.score(10, 1, &x, &y).unwrap() > 0.99);
4898    }
4899
4900    #[test]
4901    fn svm_nu_svr_fits_a_line() {
4902        let (x, y) = regression_data();
4903        let mut svm = Svm::new_nu_svr().unwrap();
4904        assert_eq!(svm.kind(), SvmKind::NuSvr);
4905        svm.handle_mut()
4906            .set_string_option("kernel", "linear")
4907            .unwrap();
4908        set_real(&mut svm, "C", 1000.0);
4909        svm.fit(10, 1, &x, &y).unwrap();
4910        let mut p = vec![0.0_f64; 10];
4911        svm.predict(10, 1, &x, &mut p).unwrap();
4912        for (g, w) in p.iter().zip(&y) {
4913            assert!((g - w).abs() < 0.5, "nu-svr pred {g} vs {w}");
4914        }
4915        assert!(svm.score(10, 1, &x, &y).unwrap() > 0.99);
4916        // Extrapolation follows the line (slope 2): f(12) ~ 25.
4917        let mut q = [0.0_f64; 1];
4918        svm.predict(1, 1, &[12.0], &mut q).unwrap();
4919        assert!((q[0] - 25.0).abs() < 1.0, "f(12) = {}", q[0]);
4920    }
4921}