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    /// Extent (rows, columns) of every selection made through this wrapper, by key: the library cannot be asked for it, and
1296    /// `extract_f64` writes exactly that block into a caller buffer it does not check.
1297    selections: std::collections::HashMap<String, (usize, usize)>,
1298}
1299
1300unsafe impl Send for Datastore {}
1301
1302impl Datastore {
1303    /// Create a fresh empty datastore.
1304    pub fn new() -> Result<Self> {
1305        let mut raw: sys::da_datastore = std::ptr::null_mut();
1306        let status = unsafe { sys::da_datastore_init(&mut raw) };
1307        check_status("data-analytics", status)?;
1308        if raw.is_null() {
1309            return Err(Error::AllocationFailed("data-analytics"));
1310        }
1311        Ok(Self {
1312            raw,
1313            selections: std::collections::HashMap::new(),
1314        })
1315    }
1316
1317    /// Set an integer-valued datastore option (e.g.
1318    /// `set_int_option("use header row", 1)`,
1319    /// `set_int_option("whitespace delimiter", 1)`).
1320    pub fn set_int_option(&mut self, name: &str, value: i64) -> Result<()> {
1321        let cs = std::ffi::CString::new(name)
1322            .map_err(|e| Error::InvalidArgument(format!("set_int_option: {e}")))?;
1323        let status = unsafe {
1324            sys::da_datastore_options_set_int(self.raw, cs.as_ptr(), value as sys::da_int)
1325        };
1326        check_status("data-analytics", status)
1327    }
1328
1329    /// Set a string-valued datastore option (e.g. `"comment"` to set a
1330    /// comment-line prefix character, `"storage order"` to choose
1331    /// row-major vs column-major).
1332    pub fn set_string_option(&mut self, name: &str, value: &str) -> Result<()> {
1333        let n = std::ffi::CString::new(name)
1334            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
1335        let v = std::ffi::CString::new(value)
1336            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
1337        let status =
1338            unsafe { sys::da_datastore_options_set_string(self.raw, n.as_ptr(), v.as_ptr()) };
1339        check_status("data-analytics", status)
1340    }
1341
1342    /// Load a CSV file into the datastore.
1343    pub fn load_csv(&mut self, path: &str) -> Result<()> {
1344        let cs = std::ffi::CString::new(path)
1345            .map_err(|e| Error::InvalidArgument(format!("load_csv: {e}")))?;
1346        let status = unsafe { sys::da_data_load_from_csv(self.raw, cs.as_ptr()) };
1347        check_status("data-analytics", status)?;
1348        // a new table: earlier selections no longer describe it
1349        self.selections.clear();
1350        Ok(())
1351    }
1352
1353    /// Number of rows currently held by the store.
1354    pub fn n_rows(&self) -> Result<usize> {
1355        let mut n: sys::da_int = 0;
1356        let status = unsafe { sys::da_data_get_n_rows(self.raw, &mut n) };
1357        check_status("data-analytics", status)?;
1358        Ok(n as usize)
1359    }
1360
1361    /// Number of columns currently held by the store.
1362    pub fn n_cols(&self) -> Result<usize> {
1363        let mut n: sys::da_int = 0;
1364        let status = unsafe { sys::da_data_get_n_cols(self.raw, &mut n) };
1365        check_status("data-analytics", status)?;
1366        Ok(n as usize)
1367    }
1368
1369    /// `(n_rows, n_cols)` dimensions.
1370    pub fn dims(&self) -> Result<(usize, usize)> {
1371        Ok((self.n_rows()?, self.n_cols()?))
1372    }
1373
1374    /// Select a contiguous range of columns into the named selection
1375    /// `key` (zero-based, inclusive bounds). Use [`Datastore::extract_f64`]
1376    /// to read the selected columns into a buffer.
1377    pub fn select_columns(&mut self, key: &str, lbound: usize, ubound: usize) -> Result<()> {
1378        let cs = std::ffi::CString::new(key)
1379            .map_err(|e| Error::InvalidArgument(format!("select_columns: {e}")))?;
1380        let status = unsafe {
1381            sys::da_data_select_columns(
1382                self.raw,
1383                cs.as_ptr(),
1384                lbound as sys::da_int,
1385                ubound as sys::da_int,
1386            )
1387        };
1388        check_status("data-analytics", status)?;
1389        let rows = self.n_rows()?;
1390        self.selections
1391            .insert(key.to_string(), (rows, ubound - lbound + 1));
1392        Ok(())
1393    }
1394
1395    /// Select a contiguous range of rows into the named selection `key`.
1396    pub fn select_rows(&mut self, key: &str, lbound: usize, ubound: usize) -> Result<()> {
1397        let cs = std::ffi::CString::new(key)
1398            .map_err(|e| Error::InvalidArgument(format!("select_rows: {e}")))?;
1399        let status = unsafe {
1400            sys::da_data_select_rows(
1401                self.raw,
1402                cs.as_ptr(),
1403                lbound as sys::da_int,
1404                ubound as sys::da_int,
1405            )
1406        };
1407        check_status("data-analytics", status)?;
1408        let cols = self.n_cols()?;
1409        self.selections
1410            .insert(key.to_string(), (ubound - lbound + 1, cols));
1411        Ok(())
1412    }
1413
1414    /// Extract the named selection into `data` as `f64` values, in the
1415    /// order specified by `layout`. `lddata` is the leading dimension
1416    /// of the output buffer.
1417    pub fn extract_f64(
1418        &self,
1419        key: &str,
1420        layout: Layout,
1421        data: &mut [f64],
1422        lddata: usize,
1423    ) -> Result<()> {
1424        let cs = std::ffi::CString::new(key)
1425            .map_err(|e| Error::InvalidArgument(format!("extract_f64: {e}")))?;
1426        let Some(&(rows, cols)) = self.selections.get(key) else {
1427            return Err(Error::InvalidArgument(format!(
1428                "extract_f64: no selection named {key:?} was made through select_columns / select_rows"
1429            )));
1430        };
1431        check_dense(
1432            "extract_f64",
1433            "data",
1434            layout,
1435            rows,
1436            cols,
1437            lddata,
1438            data.len(),
1439        )?;
1440        let status = unsafe {
1441            sys::da_data_extract_selection_real_d(
1442                self.raw,
1443                cs.as_ptr(),
1444                layout_raw(layout),
1445                data.as_mut_ptr(),
1446                lddata as sys::da_int,
1447            )
1448        };
1449        check_status("data-analytics", status)
1450    }
1451
1452    /// Borrow the raw `da_datastore` handle (for routines this crate
1453    /// doesn't yet wrap).
1454    pub fn as_raw(&self) -> sys::da_datastore {
1455        self.raw
1456    }
1457}
1458
1459impl Drop for Datastore {
1460    fn drop(&mut self) {
1461        if !self.raw.is_null() {
1462            unsafe { sys::da_datastore_destroy(&mut self.raw) };
1463            self.raw = std::ptr::null_mut();
1464        }
1465    }
1466}
1467
1468impl std::fmt::Debug for Datastore {
1469    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1470        f.debug_struct("Datastore").finish_non_exhaustive()
1471    }
1472}
1473
1474// =========================================================================
1475//   Pairwise distances
1476// =========================================================================
1477
1478/// Distance metric for [`pairwise_distances`].
1479#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1480#[non_exhaustive]
1481pub enum Metric {
1482    /// Euclidean distance (`L2`).
1483    Euclidean,
1484    /// Squared Euclidean distance (`Σ (xᵢ-yᵢ)²` without the square root).
1485    SqEuclidean,
1486    /// Minkowski distance with parameter `p` (defaults to L2 at p=2).
1487    Minkowski,
1488    /// Manhattan / `L1` / cityblock distance.
1489    Manhattan,
1490    /// Cosine distance: `1 - cos(angle)`.
1491    Cosine,
1492}
1493
1494impl Metric {
1495    fn raw(self) -> sys::da_metric {
1496        match self {
1497            Metric::Euclidean => sys::da_metric__da_euclidean,
1498            Metric::SqEuclidean => sys::da_metric__da_sqeuclidean,
1499            Metric::Minkowski => sys::da_metric__da_minkowski,
1500            Metric::Manhattan => sys::da_metric__da_manhattan,
1501            Metric::Cosine => sys::da_metric__da_cosine,
1502        }
1503    }
1504}
1505
1506/// Scalar element type usable with [`pairwise_distances`].
1507pub trait DistScalar: Scalar {
1508    /// Compute the pairwise distance matrix `D[i,j] = metric(X[i], Y[j])`.
1509    /// If `y` is `None`, distances are computed within `x` (so `D` is
1510    /// `m × m`); otherwise `D` is `m × n`.
1511    fn pairwise_distances(
1512        layout: Layout,
1513        m: usize,
1514        n: usize,
1515        k: usize,
1516        x: &[Self],
1517        ldx: usize,
1518        y: Option<&[Self]>,
1519        ldy: usize,
1520        d: &mut [Self],
1521        ldd: usize,
1522        p: Self,
1523        metric: Metric,
1524    ) -> Result<()>;
1525}
1526
1527macro_rules! impl_dist_scalar {
1528    ($t:ty, $fn:ident) => {
1529        impl DistScalar for $t {
1530            fn pairwise_distances(
1531                layout: Layout,
1532                m: usize,
1533                n: usize,
1534                k: usize,
1535                x: &[Self],
1536                ldx: usize,
1537                y: Option<&[Self]>,
1538                ldy: usize,
1539                d: &mut [Self],
1540                ldd: usize,
1541                p: Self,
1542                metric: Metric,
1543            ) -> Result<()> {
1544                check_dense("pairwise_distances", "x", layout, m, k, ldx, x.len())?;
1545                if let Some(yv) = y {
1546                    check_dense("pairwise_distances", "y", layout, n, k, ldy, yv.len())?;
1547                }
1548                let d_cols = if y.is_some() { n } else { m };
1549                check_dense("pairwise_distances", "d", layout, m, d_cols, ldd, d.len())?;
1550                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1551                let status = unsafe {
1552                    sys::$fn(
1553                        layout_raw(layout),
1554                        m as sys::da_int,
1555                        n as sys::da_int,
1556                        k as sys::da_int,
1557                        x.as_ptr(),
1558                        ldx as sys::da_int,
1559                        y_ptr,
1560                        ldy as sys::da_int,
1561                        d.as_mut_ptr(),
1562                        ldd as sys::da_int,
1563                        p,
1564                        metric.raw(),
1565                    )
1566                };
1567                check_status("data-analytics", status)
1568            }
1569        }
1570    };
1571}
1572
1573impl_dist_scalar!(f32, da_pairwise_distances_s);
1574impl_dist_scalar!(f64, da_pairwise_distances_d);
1575
1576// =========================================================================
1577//   Kernel functions (linear / RBF / polynomial / sigmoid)
1578// =========================================================================
1579
1580/// Scalar element type for kernel-matrix computations.
1581pub trait KernelScalar: Scalar {
1582    /// Linear kernel: `K(x, y) = x · y`.
1583    fn linear_kernel(
1584        layout: Layout,
1585        m: usize,
1586        n: usize,
1587        k: usize,
1588        x: &[Self],
1589        ldx: usize,
1590        y: Option<&[Self]>,
1591        ldy: usize,
1592        d: &mut [Self],
1593        ldd: usize,
1594    ) -> Result<()>;
1595
1596    /// RBF (Gaussian) kernel: `K(x, y) = exp(-γ · ‖x − y‖²)`.
1597    fn rbf_kernel(
1598        layout: Layout,
1599        m: usize,
1600        n: usize,
1601        k: usize,
1602        x: &[Self],
1603        ldx: usize,
1604        y: Option<&[Self]>,
1605        ldy: usize,
1606        d: &mut [Self],
1607        ldd: usize,
1608        gamma: Self,
1609    ) -> Result<()>;
1610
1611    /// Polynomial kernel: `K(x, y) = (γ · x · y + c)^degree`.
1612    fn polynomial_kernel(
1613        layout: Layout,
1614        m: usize,
1615        n: usize,
1616        k: usize,
1617        x: &[Self],
1618        ldx: usize,
1619        y: Option<&[Self]>,
1620        ldy: usize,
1621        d: &mut [Self],
1622        ldd: usize,
1623        gamma: Self,
1624        degree: i64,
1625        coef0: Self,
1626    ) -> Result<()>;
1627
1628    /// Sigmoid kernel: `K(x, y) = tanh(γ · x · y + c)`.
1629    fn sigmoid_kernel(
1630        layout: Layout,
1631        m: usize,
1632        n: usize,
1633        k: usize,
1634        x: &[Self],
1635        ldx: usize,
1636        y: Option<&[Self]>,
1637        ldy: usize,
1638        d: &mut [Self],
1639        ldd: usize,
1640        gamma: Self,
1641        coef0: Self,
1642    ) -> Result<()>;
1643}
1644
1645macro_rules! impl_kernel_scalar {
1646    ($t:ty, $linear:ident, $rbf:ident, $poly:ident, $sigmoid:ident) => {
1647        impl KernelScalar for $t {
1648            fn linear_kernel(
1649                layout: Layout,
1650                m: usize,
1651                n: usize,
1652                k: usize,
1653                x: &[Self],
1654                ldx: usize,
1655                y: Option<&[Self]>,
1656                ldy: usize,
1657                d: &mut [Self],
1658                ldd: usize,
1659            ) -> Result<()> {
1660                check_dense("linear_kernel", "x", layout, m, k, ldx, x.len())?;
1661                if let Some(yv) = y {
1662                    check_dense("linear_kernel", "y", layout, n, k, ldy, yv.len())?;
1663                }
1664                let d_cols = if y.is_some() { n } else { m };
1665                check_dense("linear_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1666                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1667                let status = unsafe {
1668                    sys::$linear(
1669                        layout_raw(layout),
1670                        m as sys::da_int,
1671                        n as sys::da_int,
1672                        k as sys::da_int,
1673                        x.as_ptr(),
1674                        ldx as sys::da_int,
1675                        y_ptr,
1676                        ldy as sys::da_int,
1677                        d.as_mut_ptr(),
1678                        ldd as sys::da_int,
1679                    )
1680                };
1681                check_status("data-analytics", status)
1682            }
1683
1684            fn rbf_kernel(
1685                layout: Layout,
1686                m: usize,
1687                n: usize,
1688                k: usize,
1689                x: &[Self],
1690                ldx: usize,
1691                y: Option<&[Self]>,
1692                ldy: usize,
1693                d: &mut [Self],
1694                ldd: usize,
1695                gamma: Self,
1696            ) -> Result<()> {
1697                check_dense("rbf_kernel", "x", layout, m, k, ldx, x.len())?;
1698                if let Some(yv) = y {
1699                    check_dense("rbf_kernel", "y", layout, n, k, ldy, yv.len())?;
1700                }
1701                let d_cols = if y.is_some() { n } else { m };
1702                check_dense("rbf_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1703                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1704                let status = unsafe {
1705                    sys::$rbf(
1706                        layout_raw(layout),
1707                        m as sys::da_int,
1708                        n as sys::da_int,
1709                        k as sys::da_int,
1710                        x.as_ptr(),
1711                        ldx as sys::da_int,
1712                        y_ptr,
1713                        ldy as sys::da_int,
1714                        d.as_mut_ptr(),
1715                        ldd as sys::da_int,
1716                        gamma,
1717                    )
1718                };
1719                check_status("data-analytics", status)
1720            }
1721
1722            fn polynomial_kernel(
1723                layout: Layout,
1724                m: usize,
1725                n: usize,
1726                k: usize,
1727                x: &[Self],
1728                ldx: usize,
1729                y: Option<&[Self]>,
1730                ldy: usize,
1731                d: &mut [Self],
1732                ldd: usize,
1733                gamma: Self,
1734                degree: i64,
1735                coef0: Self,
1736            ) -> Result<()> {
1737                check_dense("polynomial_kernel", "x", layout, m, k, ldx, x.len())?;
1738                if let Some(yv) = y {
1739                    check_dense("polynomial_kernel", "y", layout, n, k, ldy, yv.len())?;
1740                }
1741                let d_cols = if y.is_some() { n } else { m };
1742                check_dense("polynomial_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1743                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1744                let status = unsafe {
1745                    sys::$poly(
1746                        layout_raw(layout),
1747                        m as sys::da_int,
1748                        n as sys::da_int,
1749                        k as sys::da_int,
1750                        x.as_ptr(),
1751                        ldx as sys::da_int,
1752                        y_ptr,
1753                        ldy as sys::da_int,
1754                        d.as_mut_ptr(),
1755                        ldd as sys::da_int,
1756                        gamma,
1757                        degree as sys::da_int,
1758                        coef0,
1759                    )
1760                };
1761                check_status("data-analytics", status)
1762            }
1763
1764            fn sigmoid_kernel(
1765                layout: Layout,
1766                m: usize,
1767                n: usize,
1768                k: usize,
1769                x: &[Self],
1770                ldx: usize,
1771                y: Option<&[Self]>,
1772                ldy: usize,
1773                d: &mut [Self],
1774                ldd: usize,
1775                gamma: Self,
1776                coef0: Self,
1777            ) -> Result<()> {
1778                check_dense("sigmoid_kernel", "x", layout, m, k, ldx, x.len())?;
1779                if let Some(yv) = y {
1780                    check_dense("sigmoid_kernel", "y", layout, n, k, ldy, yv.len())?;
1781                }
1782                let d_cols = if y.is_some() { n } else { m };
1783                check_dense("sigmoid_kernel", "d", layout, m, d_cols, ldd, d.len())?;
1784                let y_ptr = y.map(|s| s.as_ptr()).unwrap_or(std::ptr::null());
1785                let status = unsafe {
1786                    sys::$sigmoid(
1787                        layout_raw(layout),
1788                        m as sys::da_int,
1789                        n as sys::da_int,
1790                        k as sys::da_int,
1791                        x.as_ptr(),
1792                        ldx as sys::da_int,
1793                        y_ptr,
1794                        ldy as sys::da_int,
1795                        d.as_mut_ptr(),
1796                        ldd as sys::da_int,
1797                        gamma,
1798                        coef0,
1799                    )
1800                };
1801                check_status("data-analytics", status)
1802            }
1803        }
1804    };
1805}
1806
1807impl_kernel_scalar!(
1808    f32,
1809    da_linear_kernel_s,
1810    da_rbf_kernel_s,
1811    da_polynomial_kernel_s,
1812    da_sigmoid_kernel_s
1813);
1814impl_kernel_scalar!(
1815    f64,
1816    da_linear_kernel_d,
1817    da_rbf_kernel_d,
1818    da_polynomial_kernel_d,
1819    da_sigmoid_kernel_d
1820);
1821
1822/// Linear kernel `K(x, y) = x · y` between rows of row-major matrices
1823/// `x` (`m × k`) and optionally `y` (`n × k`). Output `d` is `m × n`
1824/// (or `m × m` if `y` is `None`).
1825pub fn linear_kernel<T: KernelScalar>(
1826    m: usize,
1827    n: usize,
1828    k: usize,
1829    x: &[T],
1830    y: Option<&[T]>,
1831    d: &mut [T],
1832) -> Result<()> {
1833    let ldd = if y.is_none() { m } else { n };
1834    T::linear_kernel(Layout::RowMajor, m, n, k, x, k, y, k, d, ldd)
1835}
1836
1837/// RBF kernel `K(x, y) = exp(-γ · ‖x − y‖²)` (row-major).
1838pub fn rbf_kernel<T: KernelScalar>(
1839    m: usize,
1840    n: usize,
1841    k: usize,
1842    x: &[T],
1843    y: Option<&[T]>,
1844    d: &mut [T],
1845    gamma: T,
1846) -> Result<()> {
1847    let ldd = if y.is_none() { m } else { n };
1848    T::rbf_kernel(Layout::RowMajor, m, n, k, x, k, y, k, d, ldd, gamma)
1849}
1850
1851/// Polynomial kernel `K(x, y) = (γ · x · y + c)^degree` (row-major).
1852pub fn polynomial_kernel<T: KernelScalar>(
1853    m: usize,
1854    n: usize,
1855    k: usize,
1856    x: &[T],
1857    y: Option<&[T]>,
1858    d: &mut [T],
1859    gamma: T,
1860    degree: i64,
1861    coef0: T,
1862) -> Result<()> {
1863    let ldd = if y.is_none() { m } else { n };
1864    T::polynomial_kernel(
1865        Layout::RowMajor,
1866        m,
1867        n,
1868        k,
1869        x,
1870        k,
1871        y,
1872        k,
1873        d,
1874        ldd,
1875        gamma,
1876        degree,
1877        coef0,
1878    )
1879}
1880
1881/// Sigmoid kernel `K(x, y) = tanh(γ · x · y + c)` (row-major).
1882pub fn sigmoid_kernel<T: KernelScalar>(
1883    m: usize,
1884    n: usize,
1885    k: usize,
1886    x: &[T],
1887    y: Option<&[T]>,
1888    d: &mut [T],
1889    gamma: T,
1890    coef0: T,
1891) -> Result<()> {
1892    let ldd = if y.is_none() { m } else { n };
1893    T::sigmoid_kernel(Layout::RowMajor, m, n, k, x, k, y, k, d, ldd, gamma, coef0)
1894}
1895
1896/// Compute the pairwise distance matrix between rows of `x` (and
1897/// optionally rows of `y`) under the given `metric`.
1898///
1899/// `x` is `m × k` row-major; `y` (optional) is `n × k` row-major. When
1900/// `y` is `None`, distances are computed *within* `x` and the output
1901/// `d` is `m × m`. Otherwise `d` is `m × n`. `p` is the Minkowski
1902/// exponent (ignored for non-Minkowski metrics).
1903pub fn pairwise_distances<T: DistScalar>(
1904    m: usize,
1905    n: usize,
1906    k: usize,
1907    x: &[T],
1908    y: Option<&[T]>,
1909    d: &mut [T],
1910    p: T,
1911    metric: Metric,
1912) -> Result<()> {
1913    let ldd = if y.is_none() { m } else { n };
1914    let ldy = k; // row-major: ldy = k regardless of y being None
1915    T::pairwise_distances(Layout::RowMajor, m, n, k, x, k, y, ldy, d, ldd, p, metric)
1916}
1917
1918// =========================================================================
1919//   da_handle + k-means safe wrapper
1920// =========================================================================
1921
1922/// Type of analytics handle. AOCL-DA uses an opaque handle to track the
1923/// state of an algorithm (data, options, fitted model, predictions).
1924#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1925#[non_exhaustive]
1926pub enum HandleKind {
1927    Linmod,
1928    Pca,
1929    Kmeans,
1930    Dbscan,
1931    DecisionTree,
1932    DecisionForest,
1933    Knn,
1934    Svm,
1935    Nlls,
1936}
1937
1938impl HandleKind {
1939    fn raw(self) -> sys::da_handle_type {
1940        match self {
1941            HandleKind::Linmod => sys::da_handle_type__da_handle_linmod,
1942            HandleKind::Pca => sys::da_handle_type__da_handle_pca,
1943            HandleKind::Kmeans => sys::da_handle_type__da_handle_kmeans,
1944            HandleKind::Dbscan => sys::da_handle_type__da_handle_dbscan,
1945            HandleKind::DecisionTree => sys::da_handle_type__da_handle_decision_tree,
1946            HandleKind::DecisionForest => sys::da_handle_type__da_handle_decision_forest,
1947            // AOCL 5.3 renamed k-NN to nearest neighbours (`da_handle_nn`, `da_nn_*`).
1948            HandleKind::Knn => sys::da_handle_type__da_handle_nn,
1949            HandleKind::Svm => sys::da_handle_type__da_handle_svm,
1950            HandleKind::Nlls => sys::da_handle_type__da_handle_nlls,
1951        }
1952    }
1953}
1954
1955/// Internal precision selector for [`Handle`]: f64 (`Double`) or
1956/// f32 (`Single`). The choice determines which underlying `da_*_d` /
1957/// `da_*_s` C entry points are used.
1958#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1959pub enum Precision {
1960    Single,
1961    Double,
1962}
1963
1964/// RAII wrapper around `da_handle`. Tracks the algorithm and precision
1965/// chosen at construction time.
1966pub struct Handle {
1967    raw: sys::da_handle,
1968    kind: HandleKind,
1969    precision: Precision,
1970    /// A call on this handle has failed, so the library has a message stored. AOCL 6.0.68's `da_handle_get_error_message`
1971    /// on a handle with NO stored error can return success with a pointer to uninitialised heap (not a valid C string),
1972    /// so the message is only read after a failure this wrapper has seen.
1973    error_pending: std::cell::Cell<bool>,
1974}
1975
1976unsafe impl Send for Handle {}
1977
1978impl Handle {
1979    /// Create an `f64` handle for the given algorithm.
1980    pub fn new_double(kind: HandleKind) -> Result<Self> {
1981        let mut raw: sys::da_handle = std::ptr::null_mut();
1982        let status = unsafe { sys::da_handle_init_d(&mut raw, kind.raw()) };
1983        check_status("data-analytics", status)?;
1984        if raw.is_null() {
1985            return Err(Error::AllocationFailed("data-analytics"));
1986        }
1987        Ok(Self {
1988            raw,
1989            kind,
1990            precision: Precision::Double,
1991            error_pending: std::cell::Cell::new(false),
1992        })
1993    }
1994
1995    /// Create an `f32` handle.
1996    pub fn new_single(kind: HandleKind) -> Result<Self> {
1997        let mut raw: sys::da_handle = std::ptr::null_mut();
1998        let status = unsafe { sys::da_handle_init_s(&mut raw, kind.raw()) };
1999        check_status("data-analytics", status)?;
2000        if raw.is_null() {
2001            return Err(Error::AllocationFailed("data-analytics"));
2002        }
2003        Ok(Self {
2004            raw,
2005            kind,
2006            precision: Precision::Single,
2007            error_pending: std::cell::Cell::new(false),
2008        })
2009    }
2010
2011    /// Set an integer-valued option.
2012    pub fn set_int_option(&mut self, name: &str, value: i64) -> Result<()> {
2013        let cs = std::ffi::CString::new(name)
2014            .map_err(|e| Error::InvalidArgument(format!("set_int_option: {e}")))?;
2015        let status =
2016            unsafe { sys::da_options_set_int(self.raw, cs.as_ptr(), value as sys::da_int) };
2017        self.note_status(status);
2018        check_status("data-analytics", status)
2019    }
2020
2021    /// Set a string-valued option.
2022    pub fn set_string_option(&mut self, name: &str, value: &str) -> Result<()> {
2023        let n = std::ffi::CString::new(name)
2024            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
2025        let v = std::ffi::CString::new(value)
2026            .map_err(|e| Error::InvalidArgument(format!("set_string_option: {e}")))?;
2027        let status = unsafe { sys::da_options_set_string(self.raw, n.as_ptr(), v.as_ptr()) };
2028        self.note_status(status);
2029        check_status("data-analytics", status)
2030    }
2031
2032    /// Borrow the raw handle for routines this crate doesn't yet wrap.
2033    pub fn as_raw(&self) -> sys::da_handle {
2034        self.raw
2035    }
2036
2037    /// Returns `(kind, precision)`.
2038    pub fn info(&self) -> (HandleKind, Precision) {
2039        (self.kind, self.precision)
2040    }
2041
2042    /// Fetch the most recent detailed error message AOCL-DA stored on
2043    /// this handle, or `None` if there isn't one. Useful for diagnosing
2044    /// which option or input value the C library found objectionable.
2045    pub fn last_error_message(&self) -> Option<String> {
2046        if !self.error_pending.get() {
2047            // No failure seen on this handle: the library may hand back uninitialised memory here (see `error_pending`).
2048            return None;
2049        }
2050        let mut p: *mut std::os::raw::c_char = std::ptr::null_mut();
2051        let status = unsafe { sys::da_handle_get_error_message(self.raw, &mut p) };
2052        if status != sys::da_status__da_status_success || p.is_null() {
2053            return None;
2054        }
2055        let s = unsafe { std::ffi::CStr::from_ptr(p) }
2056            .to_string_lossy()
2057            .into_owned();
2058        // The library returns a freshly allocated buffer that the caller
2059        // must free with libc::free; we don't link libc here, so skip the
2060        // free. The leak is bounded (one per query) and not worth pulling
2061        // in libc just to plug.
2062        if s.is_empty() {
2063            None
2064        } else {
2065            Some(s)
2066        }
2067    }
2068
2069    /// Record that a call on this handle returned `status`: a failure means the library has an error message stored.
2070    pub(crate) fn note_status(&self, status: sys::da_status) {
2071        if status != sys::da_status__da_status_success {
2072            self.error_pending.set(true);
2073        }
2074    }
2075}
2076
2077impl Drop for Handle {
2078    fn drop(&mut self) {
2079        if !self.raw.is_null() {
2080            unsafe { sys::da_handle_destroy(&mut self.raw) };
2081            self.raw = std::ptr::null_mut();
2082        }
2083    }
2084}
2085
2086impl std::fmt::Debug for Handle {
2087    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2088        f.debug_struct("Handle")
2089            .field("kind", &self.kind)
2090            .field("precision", &self.precision)
2091            .finish_non_exhaustive()
2092    }
2093}
2094
2095/// k-means clustering wrapper. Holds an [`Handle`] specialised for
2096/// `da_handle_kmeans` and exposes the typical fit/predict interface.
2097pub struct KMeans {
2098    handle: Handle,
2099}
2100
2101impl KMeans {
2102    /// Build a new k-means model with `n_clusters` clusters in `f64`
2103    /// precision.
2104    pub fn new(n_clusters: usize) -> Result<Self> {
2105        let mut handle = Handle::new_double(HandleKind::Kmeans)?;
2106        handle.set_int_option("n_clusters", n_clusters as i64)?;
2107        Ok(Self { handle })
2108    }
2109
2110    /// Fit on `n_samples × n_features` data matrix in **column-major**
2111    /// layout (one column per feature; `lda = n_samples`). This matches
2112    /// AOCL-DA's default storage convention.
2113    pub fn fit(&mut self, n_samples: usize, n_features: usize, data: &[f64]) -> Result<()> {
2114        if data.len() < n_samples * n_features {
2115            return Err(Error::InvalidArgument(format!(
2116                "fit: data length {} < n_samples·n_features = {}",
2117                data.len(),
2118                n_samples * n_features
2119            )));
2120        }
2121        let lda = n_samples;
2122        let status = unsafe {
2123            sys::da_kmeans_set_data_d(
2124                self.handle.raw,
2125                n_samples as sys::da_int,
2126                n_features as sys::da_int,
2127                data.as_ptr(),
2128                lda as sys::da_int,
2129            )
2130        };
2131        check_status("data-analytics", status)?;
2132        let status = unsafe { sys::da_kmeans_compute_d(self.handle.raw) };
2133        check_status("data-analytics", status)
2134    }
2135
2136    /// Predict cluster labels for new samples in column-major layout.
2137    pub fn predict(
2138        &mut self,
2139        k_samples: usize,
2140        k_features: usize,
2141        y: &[f64],
2142        labels: &mut [i32],
2143    ) -> Result<()> {
2144        check_dense(
2145            "kmeans predict",
2146            "y",
2147            Layout::ColMajor,
2148            k_samples,
2149            k_features,
2150            k_samples,
2151            y.len(),
2152        )?;
2153        if labels.len() < k_samples {
2154            return Err(Error::InvalidArgument(format!(
2155                "predict: labels length {} < k_samples = {k_samples}",
2156                labels.len()
2157            )));
2158        }
2159        let mut out = IntsOut::new(k_samples);
2160        let status = unsafe {
2161            sys::da_kmeans_predict_d(
2162                self.handle.raw,
2163                k_samples as sys::da_int,
2164                k_features as sys::da_int,
2165                y.as_ptr(),
2166                k_samples as sys::da_int,
2167                out.as_mut_ptr(),
2168            )
2169        };
2170        check_status("data-analytics", status)?;
2171        out.write_back(labels, k_samples)
2172    }
2173}
2174
2175impl std::fmt::Debug for KMeans {
2176    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2177        f.debug_struct("KMeans")
2178            .field("handle", &self.handle)
2179            .finish()
2180    }
2181}
2182
2183/// Principal Component Analysis. Reduces an `n_samples × n_features`
2184/// matrix to a lower-dimensional representation.
2185pub struct Pca {
2186    handle: Handle,
2187}
2188
2189impl Pca {
2190    /// Build a new PCA handle that retains `n_components` principal
2191    /// directions, in `f64` precision.
2192    pub fn new(n_components: usize) -> Result<Self> {
2193        let mut handle = Handle::new_double(HandleKind::Pca)?;
2194        handle.set_int_option("n_components", n_components as i64)?;
2195        Ok(Self { handle })
2196    }
2197
2198    /// Fit on column-major `n_samples × n_features` data.
2199    pub fn fit(&mut self, n_samples: usize, n_features: usize, data: &[f64]) -> Result<()> {
2200        if data.len() < n_samples * n_features {
2201            return Err(Error::InvalidArgument(format!(
2202                "PCA fit: data length {} < n_samples·n_features = {}",
2203                data.len(),
2204                n_samples * n_features
2205            )));
2206        }
2207        let lda = n_samples;
2208        let status = unsafe {
2209            sys::da_pca_set_data_d(
2210                self.handle.raw,
2211                n_samples as sys::da_int,
2212                n_features as sys::da_int,
2213                data.as_ptr(),
2214                lda as sys::da_int,
2215            )
2216        };
2217        check_status("data-analytics", status)?;
2218        let status = unsafe { sys::da_pca_compute_d(self.handle.raw) };
2219        check_status("data-analytics", status)
2220    }
2221
2222    /// Project `m_samples × m_features` new data into the fitted
2223    /// principal-component space. `out` receives the transformed
2224    /// `m_samples × n_components` matrix in column-major layout
2225    /// (`ldx_transform = m_samples`).
2226    pub fn transform(
2227        &mut self,
2228        m_samples: usize,
2229        m_features: usize,
2230        x: &[f64],
2231        n_components: usize,
2232        out: &mut [f64],
2233    ) -> Result<()> {
2234        if x.len() < m_samples * m_features {
2235            return Err(Error::InvalidArgument(format!(
2236                "PCA transform: x length {} < m_samples·m_features = {}",
2237                x.len(),
2238                m_samples * m_features
2239            )));
2240        }
2241        if out.len() < m_samples * n_components {
2242            return Err(Error::InvalidArgument(format!(
2243                "PCA transform: out length {} < m_samples·n_components = {}",
2244                out.len(),
2245                m_samples * n_components
2246            )));
2247        }
2248        let status = unsafe {
2249            sys::da_pca_transform_d(
2250                self.handle.raw,
2251                m_samples as sys::da_int,
2252                m_features as sys::da_int,
2253                x.as_ptr(),
2254                m_samples as sys::da_int,
2255                out.as_mut_ptr(),
2256                m_samples as sys::da_int,
2257            )
2258        };
2259        check_status("data-analytics", status)
2260    }
2261}
2262
2263impl std::fmt::Debug for Pca {
2264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2265        f.debug_struct("Pca").field("handle", &self.handle).finish()
2266    }
2267}
2268
2269// ---------------------------------------------------------------------------
2270//   Width-correct integer buffers
2271// ---------------------------------------------------------------------------
2272//
2273// The safe API takes and returns `i32` labels, indices and class ids, but the library's `da_int` is 32-bit under LP64
2274// and 64-bit under ILP64. Handing it a pointer cast from an `i32` slice is only right for LP64 (under ILP64 it reads
2275// and writes 8 bytes per element: measured, an access violation), so every integer array goes through a `da_int`
2276// buffer and is narrowed back with a range check.
2277
2278/// Copy `i32` values into a `da_int` buffer.
2279fn ints_in(x: &[i32]) -> Vec<sys::da_int> {
2280    x.iter().map(|&v| v as sys::da_int).collect()
2281}
2282
2283/// A `da_int` output buffer that is narrowed back into the caller's `&mut [i32]`.
2284struct IntsOut {
2285    buf: Vec<sys::da_int>,
2286}
2287
2288impl IntsOut {
2289    fn new(len: usize) -> Self {
2290        Self {
2291            buf: vec![0; len.max(1)],
2292        }
2293    }
2294    fn as_mut_ptr(&mut self) -> *mut sys::da_int {
2295        self.buf.as_mut_ptr()
2296    }
2297    /// Copy the first `n` results into `out`, failing if a value does not fit in `i32`.
2298    fn write_back(&self, out: &mut [i32], n: usize) -> Result<()> {
2299        for (o, &v) in out.iter_mut().zip(self.buf.iter()).take(n) {
2300            *o = narrow_da_int(v)?;
2301        }
2302        Ok(())
2303    }
2304}
2305
2306/// Narrow a library `da_int` to `i32`, failing if it does not fit.
2307///
2308/// `da_int` is `i32` under LP64 (the conversion is then the identity) and
2309/// `i64` under the `ilp64` feature (the conversion can fail), so the lint that
2310/// fires on the LP64 build is a false positive for the crate as a whole.
2311#[allow(clippy::useless_conversion)]
2312fn narrow_da_int(v: sys::da_int) -> Result<i32> {
2313    i32::try_from(v).map_err(|_| {
2314        Error::InvalidArgument(format!(
2315            "the library returned {v}, which does not fit in i32"
2316        ))
2317    })
2318}
2319
2320/// k-nearest-neighbours classifier.
2321pub struct KNearestNeighbours {
2322    handle: Handle,
2323    // `da_nn_set_data_d` / `da_nn_set_labels_d` store pointers, not copies, so the training data is owned here.
2324    train_x: Vec<f64>,
2325    train_y: Vec<sys::da_int>,
2326}
2327
2328impl KNearestNeighbours {
2329    /// Build a new k-NN classifier in `f64` precision. The number of
2330    /// neighbours `k` defaults to AOCL-DA's built-in default (commonly
2331    /// 5); call [`KNearestNeighbours::handle_mut`] and
2332    /// `set_int_option` to override it (the option name is AOCL-version
2333    /// specific — try `"number of neighbours"`).
2334    pub fn new() -> Result<Self> {
2335        let handle = Handle::new_double(HandleKind::Knn)?;
2336        Ok(Self {
2337            handle,
2338            train_x: Vec::new(),
2339            train_y: Vec::new(),
2340        })
2341    }
2342
2343    /// Borrow the underlying handle to set algorithm-specific options.
2344    pub fn handle_mut(&mut self) -> &mut Handle {
2345        &mut self.handle
2346    }
2347
2348    /// Fit with `n_samples × n_features` training data (column-major)
2349    /// and a `n_samples` integer label vector.
2350    pub fn fit(
2351        &mut self,
2352        n_samples: usize,
2353        n_features: usize,
2354        x_train: &[f64],
2355        y_train: &[i32],
2356    ) -> Result<()> {
2357        if x_train.len() < n_samples * n_features {
2358            return Err(Error::InvalidArgument(format!(
2359                "knn fit: x_train length {} < n_samples·n_features = {}",
2360                x_train.len(),
2361                n_samples * n_features
2362            )));
2363        }
2364        if y_train.len() < n_samples {
2365            return Err(Error::InvalidArgument(format!(
2366                "knn fit: y_train length {} < n_samples = {n_samples}",
2367                y_train.len()
2368            )));
2369        }
2370        self.train_x = x_train[..n_samples * n_features].to_vec();
2371        self.train_y = ints_in(&y_train[..n_samples]);
2372        let status = unsafe {
2373            sys::da_nn_set_data_d(
2374                self.handle.raw,
2375                n_samples as sys::da_int,
2376                n_features as sys::da_int,
2377                self.train_x.as_ptr(),
2378                n_samples as sys::da_int,
2379            )
2380        };
2381        check_status("data-analytics", status)?;
2382        let status = unsafe {
2383            sys::da_nn_set_labels_d(
2384                self.handle.raw,
2385                n_samples as sys::da_int,
2386                self.train_y.as_ptr(),
2387            )
2388        };
2389        check_status("data-analytics", status)
2390    }
2391
2392    /// Predict labels for `n_queries × n_features` samples (column-major).
2393    pub fn predict(
2394        &mut self,
2395        n_queries: usize,
2396        n_features: usize,
2397        x_test: &[f64],
2398        labels: &mut [i32],
2399    ) -> Result<()> {
2400        if x_test.len() < n_queries * n_features {
2401            return Err(Error::InvalidArgument(format!(
2402                "knn predict: x_test length {} < n_queries·n_features = {}",
2403                x_test.len(),
2404                n_queries * n_features
2405            )));
2406        }
2407        if labels.len() < n_queries {
2408            return Err(Error::InvalidArgument(format!(
2409                "knn predict: labels length {} < n_queries = {n_queries}",
2410                labels.len()
2411            )));
2412        }
2413        let mut out = IntsOut::new(n_queries);
2414        let status = unsafe {
2415            sys::da_nn_classifier_predict_d(
2416                self.handle.raw,
2417                n_queries as sys::da_int,
2418                n_features as sys::da_int,
2419                x_test.as_ptr(),
2420                n_queries as sys::da_int,
2421                out.as_mut_ptr(),
2422                sys::da_nn_search_mode__knn_search_mode,
2423            )
2424        };
2425        check_status("data-analytics", status)?;
2426        out.write_back(labels, n_queries)
2427    }
2428
2429    /// For each of `n_queries` test rows, write into `n_ind` (length
2430    /// `n_queries · k`) the column-major indices of its `k` nearest
2431    /// training-set neighbours. If `return_distance` is true, also fill
2432    /// `n_dist` (same shape) with the distances.
2433    pub fn kneighbors(
2434        &mut self,
2435        n_queries: usize,
2436        n_features: usize,
2437        x_test: &[f64],
2438        n_ind: &mut [i32],
2439        n_dist: &mut [f64],
2440        k: usize,
2441        return_distance: bool,
2442    ) -> Result<()> {
2443        check_dense(
2444            "kneighbors",
2445            "x_test",
2446            Layout::ColMajor,
2447            n_queries,
2448            n_features,
2449            n_queries,
2450            x_test.len(),
2451        )?;
2452        if n_ind.len() < n_queries * k {
2453            return Err(Error::InvalidArgument(format!(
2454                "kneighbors: n_ind has {} elements, {} are needed",
2455                n_ind.len(),
2456                n_queries * k
2457            )));
2458        }
2459        if return_distance {
2460            check_dense(
2461                "kneighbors",
2462                "n_dist",
2463                Layout::ColMajor,
2464                n_queries,
2465                k,
2466                n_queries,
2467                n_dist.len(),
2468            )?;
2469        }
2470        let mut out = IntsOut::new(n_ind.len());
2471        let status = unsafe {
2472            sys::da_nn_kneighbors_d(
2473                self.handle.raw,
2474                n_queries as sys::da_int,
2475                n_features as sys::da_int,
2476                x_test.as_ptr(),
2477                n_queries as sys::da_int,
2478                out.as_mut_ptr(),
2479                n_dist.as_mut_ptr(),
2480                k as sys::da_int,
2481                if return_distance { 1 } else { 0 } as sys::da_int,
2482            )
2483        };
2484        check_status("data-analytics", status)?;
2485        out.write_back(n_ind, n_queries * k)
2486    }
2487
2488    /// Retrieve the unique class labels seen during training, ascending,
2489    /// into `classes` (at most `classes.len()` of them). Returns the
2490    /// number of classes, which may exceed `classes.len()`.
2491    pub fn classes(&self, classes: &mut [i32]) -> Result<usize> {
2492        // `n_classes` is in/out: a value > 0 on entry is taken as the number of classes (the library then writes that
2493        // many entries, past its own array when the caller's buffer is merely large), so ask for the count with 0 first.
2494        let mut n_classes: sys::da_int = 0;
2495        let status =
2496            unsafe { sys::da_nn_classes_d(self.handle.raw, &mut n_classes, std::ptr::null_mut()) };
2497        check_status("data-analytics", status)?;
2498        let total = n_classes.max(0) as usize;
2499        if total == 0 {
2500            return Ok(0);
2501        }
2502        let mut out = IntsOut::new(total);
2503        let mut n_again: sys::da_int = total as sys::da_int;
2504        let status =
2505            unsafe { sys::da_nn_classes_d(self.handle.raw, &mut n_again, out.as_mut_ptr()) };
2506        check_status("data-analytics", status)?;
2507        out.write_back(classes, total.min(classes.len()))?;
2508        Ok(total)
2509    }
2510
2511    /// Probability estimates: `n_queries × n_classes` column-major matrix
2512    /// at `proba` (element (query, class) at `class * n_queries + query`). Use [`KNearestNeighbours::classes`] to discover
2513    /// which class each column corresponds to.
2514    pub fn predict_proba(
2515        &mut self,
2516        n_queries: usize,
2517        n_features: usize,
2518        x_test: &[f64],
2519        proba: &mut [f64],
2520    ) -> Result<()> {
2521        check_dense(
2522            "predict_proba",
2523            "x_test",
2524            Layout::ColMajor,
2525            n_queries,
2526            n_features,
2527            n_queries,
2528            x_test.len(),
2529        )?;
2530        let n_classes = {
2531            let mut c = self.train_y.clone();
2532            c.sort_unstable();
2533            c.dedup();
2534            c.len()
2535        };
2536        check_dense(
2537            "predict_proba",
2538            "proba",
2539            Layout::ColMajor,
2540            n_queries,
2541            n_classes,
2542            n_queries,
2543            proba.len(),
2544        )?;
2545        let status = unsafe {
2546            sys::da_nn_classifier_predict_proba_d(
2547                self.handle.raw,
2548                n_queries as sys::da_int,
2549                n_features as sys::da_int,
2550                x_test.as_ptr(),
2551                n_queries as sys::da_int,
2552                proba.as_mut_ptr(),
2553                sys::da_nn_search_mode__knn_search_mode,
2554            )
2555        };
2556        check_status("data-analytics", status)
2557    }
2558}
2559
2560impl std::fmt::Debug for KNearestNeighbours {
2561    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2562        f.debug_struct("KNearestNeighbours")
2563            .field("handle", &self.handle)
2564            .finish()
2565    }
2566}
2567
2568// =========================================================================
2569//   Linear models (linmod)
2570// =========================================================================
2571
2572/// Family of linear model handled by [`Linmod`].
2573#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2574#[non_exhaustive]
2575pub enum LinmodKind {
2576    /// L2 (least-squares) linear regression.
2577    Mse,
2578    /// Logistic regression for classification.
2579    Logistic,
2580}
2581
2582impl LinmodKind {
2583    fn raw(self) -> sys::linmod_model {
2584        match self {
2585            LinmodKind::Mse => sys::linmod_model__linmod_model_mse,
2586            LinmodKind::Logistic => sys::linmod_model__linmod_model_logistic,
2587        }
2588    }
2589}
2590
2591/// Linear-model wrapper covering least-squares (MSE) regression and
2592/// logistic regression. Use [`Linmod::fit`] to fit the model on training
2593/// data, then [`Linmod::coefficients`] to inspect the fitted weights or
2594/// [`Linmod::predict`] / [`Linmod::evaluate`] to apply the model.
2595///
2596/// Data is laid out **column-major** by default (one column per feature,
2597/// `lda = n_samples`). To pass row-major data, call
2598/// [`Linmod::handle_mut`] and `set_string_option("storage order",
2599/// "row-major")` before fitting.
2600pub struct Linmod {
2601    handle: Handle,
2602    kind: LinmodKind,
2603    n_features_at_fit: Option<usize>,
2604}
2605
2606impl Linmod {
2607    /// Build a new MSE (L2) regression model in `f64` precision.
2608    pub fn new_mse() -> Result<Self> {
2609        Self::new_with(LinmodKind::Mse)
2610    }
2611
2612    /// Build a new logistic regression model in `f64` precision.
2613    pub fn new_logistic() -> Result<Self> {
2614        Self::new_with(LinmodKind::Logistic)
2615    }
2616
2617    fn new_with(kind: LinmodKind) -> Result<Self> {
2618        let handle = Handle::new_double(HandleKind::Linmod)?;
2619        let status = unsafe { sys::da_linmod_select_model_d(handle.raw, kind.raw()) };
2620        check_status("data-analytics", status)?;
2621        Ok(Self {
2622            handle,
2623            kind,
2624            n_features_at_fit: None,
2625        })
2626    }
2627
2628    /// Borrow the underlying handle to set algorithm-specific options
2629    /// (regularisation, solver choice, storage order, …).
2630    pub fn handle_mut(&mut self) -> &mut Handle {
2631        &mut self.handle
2632    }
2633
2634    /// Family of linear model that this handle was constructed for.
2635    pub fn kind(&self) -> LinmodKind {
2636        self.kind
2637    }
2638
2639    /// Fit the model on `n_samples × n_features` training data (column-major
2640    /// by default) with a length-`n_samples` response vector `y`.
2641    pub fn fit(&mut self, n_samples: usize, n_features: usize, x: &[f64], y: &[f64]) -> Result<()> {
2642        if x.len() < n_samples * n_features {
2643            return Err(Error::InvalidArgument(format!(
2644                "linmod fit: x length {} < n_samples·n_features = {}",
2645                x.len(),
2646                n_samples * n_features
2647            )));
2648        }
2649        if y.len() < n_samples {
2650            return Err(Error::InvalidArgument(format!(
2651                "linmod fit: y length {} < n_samples = {n_samples}",
2652                y.len()
2653            )));
2654        }
2655        let status = unsafe {
2656            sys::da_linmod_define_features_d(
2657                self.handle.raw,
2658                n_samples as sys::da_int,
2659                n_features as sys::da_int,
2660                x.as_ptr(),
2661                n_samples as sys::da_int, // ldx: column-major, the default storage order
2662                y.as_ptr(),
2663            )
2664        };
2665        if status != sys::da_status__da_status_success {
2666            self.handle.note_status(status);
2667            let extra = self.handle.last_error_message().unwrap_or_default();
2668            return Err(Error::Status {
2669                component: "data-analytics",
2670                code: status as i64,
2671                message: format!("linmod define_features failed: {extra}"),
2672            });
2673        }
2674        let status = unsafe { sys::da_linmod_fit_d(self.handle.raw) };
2675        if status != sys::da_status__da_status_success {
2676            self.handle.note_status(status);
2677            let extra = self.handle.last_error_message().unwrap_or_default();
2678            return Err(Error::Status {
2679                component: "data-analytics",
2680                code: status as i64,
2681                message: format!("linmod fit failed: {extra}"),
2682            });
2683        }
2684        self.n_features_at_fit = Some(n_features);
2685        Ok(())
2686    }
2687
2688    /// Retrieve the fitted model coefficients. For MSE regression with no
2689    /// intercept this is a vector of length `n_features`; with an intercept
2690    /// or for logistic regression it may be longer (the library decides
2691    /// the layout).
2692    pub fn coefficients(&self) -> Result<Vec<f64>> {
2693        // AOCL's size-discovery pattern: call with a buffer that may be
2694        // too small. On `invalid_array_dimension`, `dim` is updated with
2695        // the required size; resize and call again.
2696        let mut dim: sys::da_int = 1;
2697        let mut tmp = [0.0_f64; 1];
2698        let probe = unsafe {
2699            sys::da_handle_get_result_d(
2700                self.handle.raw,
2701                sys::da_result__da_linmod_coef,
2702                &mut dim,
2703                tmp.as_mut_ptr(),
2704            )
2705        };
2706        if probe == sys::da_status__da_status_success {
2707            return Ok(tmp[..dim as usize].to_vec());
2708        }
2709        if probe != sys::da_status__da_status_invalid_array_dimension {
2710            self.handle.note_status(probe);
2711            let extra = self.handle.last_error_message().unwrap_or_default();
2712            return Err(Error::Status {
2713                component: "data-analytics",
2714                code: probe as i64,
2715                message: format!("linmod coefficients (probe): {extra}"),
2716            });
2717        }
2718        if dim <= 0 {
2719            return Err(Error::Status {
2720                component: "data-analytics",
2721                code: probe as i64,
2722                message: "linmod coefficients: solver did not report a size".into(),
2723            });
2724        }
2725        let mut out = vec![0.0_f64; dim as usize];
2726        let status = unsafe {
2727            sys::da_handle_get_result_d(
2728                self.handle.raw,
2729                sys::da_result__da_linmod_coef,
2730                &mut dim,
2731                out.as_mut_ptr(),
2732            )
2733        };
2734        if status != sys::da_status__da_status_success {
2735            self.handle.note_status(status);
2736            let extra = self.handle.last_error_message().unwrap_or_default();
2737            return Err(Error::Status {
2738                component: "data-analytics",
2739                code: status as i64,
2740                message: format!("linmod coefficients: {extra}"),
2741            });
2742        }
2743        out.truncate(dim as usize);
2744        Ok(out)
2745    }
2746
2747    /// Apply the model to `n_samples × n_features` new data, writing
2748    /// `n_samples` predicted values into `predictions`. For MSE regression
2749    /// these are continuous responses; for logistic regression they are
2750    /// integer class indices stored as floats.
2751    pub fn predict(
2752        &mut self,
2753        n_samples: usize,
2754        n_features: usize,
2755        x: &[f64],
2756        predictions: &mut [f64],
2757    ) -> Result<()> {
2758        if let Some(expected) = self.n_features_at_fit {
2759            if expected != n_features {
2760                return Err(Error::InvalidArgument(format!(
2761                    "linmod predict: n_features {n_features} != fit-time {expected}"
2762                )));
2763            }
2764        }
2765        if x.len() < n_samples * n_features {
2766            return Err(Error::InvalidArgument(format!(
2767                "linmod predict: x length {} < n_samples·n_features = {}",
2768                x.len(),
2769                n_samples * n_features
2770            )));
2771        }
2772        if predictions.len() < n_samples {
2773            return Err(Error::InvalidArgument(format!(
2774                "linmod predict: predictions length {} < n_samples = {n_samples}",
2775                predictions.len()
2776            )));
2777        }
2778        let status = unsafe {
2779            sys::da_linmod_evaluate_model_d(
2780                self.handle.raw,
2781                n_samples as sys::da_int,
2782                n_features as sys::da_int,
2783                x.as_ptr(),
2784                n_samples as sys::da_int, // ldx: column-major, the default storage order
2785                predictions.as_mut_ptr(),
2786                std::ptr::null_mut(),
2787                std::ptr::null_mut(),
2788            )
2789        };
2790        check_status("data-analytics", status)
2791    }
2792
2793    /// Apply the model and also compute the model loss against the
2794    /// supplied observations `y`. Returns the scalar loss.
2795    pub fn evaluate(
2796        &mut self,
2797        n_samples: usize,
2798        n_features: usize,
2799        x: &[f64],
2800        y: &[f64],
2801        predictions: &mut [f64],
2802    ) -> Result<f64> {
2803        if y.len() < n_samples {
2804            return Err(Error::InvalidArgument(format!(
2805                "linmod evaluate: y length {} < n_samples = {n_samples}",
2806                y.len()
2807            )));
2808        }
2809        if x.len() < n_samples * n_features {
2810            return Err(Error::InvalidArgument(format!(
2811                "linmod evaluate: x length {} < n_samples·n_features = {}",
2812                x.len(),
2813                n_samples * n_features
2814            )));
2815        }
2816        if predictions.len() < n_samples {
2817            return Err(Error::InvalidArgument(format!(
2818                "linmod evaluate: predictions length {} < n_samples = {n_samples}",
2819                predictions.len()
2820            )));
2821        }
2822        // The C API takes `observations` as *mut despite logically being
2823        // input; copy `y` into a local buffer to keep the callsite safe.
2824        let mut y_buf = y.to_vec();
2825        let mut loss = 0.0_f64;
2826        let status = unsafe {
2827            sys::da_linmod_evaluate_model_d(
2828                self.handle.raw,
2829                n_samples as sys::da_int,
2830                n_features as sys::da_int,
2831                x.as_ptr(),
2832                n_samples as sys::da_int, // ldx: column-major, the default storage order
2833                predictions.as_mut_ptr(),
2834                y_buf.as_mut_ptr(),
2835                &mut loss,
2836            )
2837        };
2838        check_status("data-analytics", status)?;
2839        Ok(loss)
2840    }
2841}
2842
2843impl std::fmt::Debug for Linmod {
2844    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2845        f.debug_struct("Linmod")
2846            .field("kind", &self.kind)
2847            .field("handle", &self.handle)
2848            .finish()
2849    }
2850}
2851
2852// =========================================================================
2853//   DBSCAN clustering
2854// =========================================================================
2855
2856/// DBSCAN density-based clustering. Unlike k-means it does not require
2857/// the number of clusters in advance and can mark points as noise
2858/// (label `-1`).
2859///
2860/// Configure with options like `"eps"` and `"min_samples"` via
2861/// [`Dbscan::handle_mut`] before [`Dbscan::fit`]; defaults follow
2862/// scikit-learn's conventions.
2863pub struct Dbscan {
2864    handle: Handle,
2865    n_samples_at_fit: Option<usize>,
2866}
2867
2868impl Dbscan {
2869    /// Build a new DBSCAN handle in `f64` precision.
2870    pub fn new() -> Result<Self> {
2871        let handle = Handle::new_double(HandleKind::Dbscan)?;
2872        Ok(Self {
2873            handle,
2874            n_samples_at_fit: None,
2875        })
2876    }
2877
2878    /// Borrow the underlying handle to set DBSCAN-specific options:
2879    /// e.g. `set_string_option("metric", "euclidean")`,
2880    /// `set_int_option("min samples", 5)`, or for the real-valued
2881    /// `eps` use `da_options_set_real_d` directly via [`Handle::as_raw`].
2882    pub fn handle_mut(&mut self) -> &mut Handle {
2883        &mut self.handle
2884    }
2885
2886    /// Fit on column-major `n_samples × n_features` data matrix.
2887    pub fn fit(&mut self, n_samples: usize, n_features: usize, data: &[f64]) -> Result<()> {
2888        if data.len() < n_samples * n_features {
2889            return Err(Error::InvalidArgument(format!(
2890                "dbscan fit: data length {} < n_samples·n_features = {}",
2891                data.len(),
2892                n_samples * n_features
2893            )));
2894        }
2895        let lda = n_samples;
2896        let status = unsafe {
2897            sys::da_dbscan_set_data_d(
2898                self.handle.raw,
2899                n_samples as sys::da_int,
2900                n_features as sys::da_int,
2901                data.as_ptr(),
2902                lda as sys::da_int,
2903            )
2904        };
2905        if status != sys::da_status__da_status_success {
2906            self.handle.note_status(status);
2907            let extra = self.handle.last_error_message().unwrap_or_default();
2908            return Err(Error::Status {
2909                component: "data-analytics",
2910                code: status as i64,
2911                message: format!("dbscan set_data failed: {extra}"),
2912            });
2913        }
2914        let status = unsafe { sys::da_dbscan_compute_d(self.handle.raw) };
2915        if status != sys::da_status__da_status_success {
2916            self.handle.note_status(status);
2917            let extra = self.handle.last_error_message().unwrap_or_default();
2918            return Err(Error::Status {
2919                component: "data-analytics",
2920                code: status as i64,
2921                message: format!("dbscan compute failed: {extra}"),
2922            });
2923        }
2924        self.n_samples_at_fit = Some(n_samples);
2925        Ok(())
2926    }
2927
2928    /// Number of clusters discovered (excludes noise).
2929    pub fn n_clusters(&self) -> Result<usize> {
2930        let mut dim: sys::da_int = 1;
2931        let mut buf = [0_i64 as sys::da_int; 1];
2932        let status = unsafe {
2933            sys::da_handle_get_result_int(
2934                self.handle.raw,
2935                sys::da_result__da_dbscan_n_clusters,
2936                &mut dim,
2937                buf.as_mut_ptr(),
2938            )
2939        };
2940        check_status("data-analytics", status)?;
2941        Ok(buf[0] as usize)
2942    }
2943
2944    /// Number of *core* samples (points that have at least `min_samples`
2945    /// neighbours within distance `eps`).
2946    pub fn n_core_samples(&self) -> Result<usize> {
2947        let mut dim: sys::da_int = 1;
2948        let mut buf = [0_i64 as sys::da_int; 1];
2949        let status = unsafe {
2950            sys::da_handle_get_result_int(
2951                self.handle.raw,
2952                sys::da_result__da_dbscan_n_core_samples,
2953                &mut dim,
2954                buf.as_mut_ptr(),
2955            )
2956        };
2957        check_status("data-analytics", status)?;
2958        Ok(buf[0] as usize)
2959    }
2960
2961    /// Labels assigned to each input sample. `-1` indicates noise; other
2962    /// values index a cluster `0 .. n_clusters()`.
2963    pub fn labels(&self) -> Result<Vec<i32>> {
2964        let n = self.n_samples_at_fit.ok_or_else(|| {
2965            Error::InvalidArgument("dbscan labels: model has not been fit yet".into())
2966        })?;
2967        let mut dim: sys::da_int = n as sys::da_int;
2968        let mut out: Vec<sys::da_int> = vec![0; n];
2969        let status = unsafe {
2970            sys::da_handle_get_result_int(
2971                self.handle.raw,
2972                sys::da_result__da_dbscan_labels,
2973                &mut dim,
2974                out.as_mut_ptr(),
2975            )
2976        };
2977        check_status("data-analytics", status)?;
2978        out.truncate(dim as usize);
2979        out.into_iter().map(narrow_da_int).collect()
2980    }
2981
2982    /// Indices of the core samples (length = `n_core_samples()`).
2983    pub fn core_sample_indices(&self) -> Result<Vec<i32>> {
2984        let n_core = self.n_core_samples()?;
2985        let mut dim: sys::da_int = n_core as sys::da_int;
2986        let mut out: Vec<sys::da_int> = vec![0; n_core];
2987        if n_core == 0 {
2988            return Ok(Vec::new());
2989        }
2990        let status = unsafe {
2991            sys::da_handle_get_result_int(
2992                self.handle.raw,
2993                sys::da_result__da_dbscan_core_sample_indices,
2994                &mut dim,
2995                out.as_mut_ptr(),
2996            )
2997        };
2998        check_status("data-analytics", status)?;
2999        out.truncate(dim as usize);
3000        out.into_iter().map(narrow_da_int).collect()
3001    }
3002}
3003
3004impl std::fmt::Debug for Dbscan {
3005    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3006        f.debug_struct("Dbscan")
3007            .field("handle", &self.handle)
3008            .finish()
3009    }
3010}
3011
3012// =========================================================================
3013//   Decision tree / forest
3014// =========================================================================
3015
3016/// A single decision tree classifier. Configure tree-specific options
3017/// such as `"maximum depth"` or `"minimum samples per split"` via
3018/// [`DecisionTree::handle_mut`] before calling [`DecisionTree::fit`].
3019pub struct DecisionTree {
3020    handle: Handle,
3021}
3022
3023impl DecisionTree {
3024    /// Build a new decision-tree handle in `f64` precision.
3025    pub fn new() -> Result<Self> {
3026        let handle = Handle::new_double(HandleKind::DecisionTree)?;
3027        Ok(Self { handle })
3028    }
3029
3030    /// Borrow the underlying handle to set tree options.
3031    pub fn handle_mut(&mut self) -> &mut Handle {
3032        &mut self.handle
3033    }
3034
3035    /// Fit on column-major `n_samples × n_features` features `x` with
3036    /// integer class labels `y`. `n_class = 0` lets AOCL infer it from
3037    /// the label distribution.
3038    pub fn fit(
3039        &mut self,
3040        n_samples: usize,
3041        n_features: usize,
3042        n_class: usize,
3043        x: &[f64],
3044        y: &[i32],
3045    ) -> Result<()> {
3046        if x.len() < n_samples * n_features {
3047            return Err(Error::InvalidArgument(format!(
3048                "tree fit: x length {} < n_samples·n_features = {}",
3049                x.len(),
3050                n_samples * n_features
3051            )));
3052        }
3053        if y.len() < n_samples {
3054            return Err(Error::InvalidArgument(format!(
3055                "tree fit: y length {} < n_samples = {n_samples}",
3056                y.len()
3057            )));
3058        }
3059        let lda = n_samples;
3060        let y_da = ints_in(&y[..n_samples]);
3061        let status = unsafe {
3062            sys::da_tree_set_training_data_d(
3063                self.handle.raw,
3064                n_samples as sys::da_int,
3065                n_features as sys::da_int,
3066                n_class as sys::da_int,
3067                x.as_ptr(),
3068                lda as sys::da_int,
3069                y_da.as_ptr(),
3070                std::ptr::null(), // categorical_features: none (argument added in AOCL 5.3)
3071            )
3072        };
3073        if status != sys::da_status__da_status_success {
3074            self.handle.note_status(status);
3075            let extra = self.handle.last_error_message().unwrap_or_default();
3076            return Err(Error::Status {
3077                component: "data-analytics",
3078                code: status as i64,
3079                message: format!("tree set_training_data failed: {extra}"),
3080            });
3081        }
3082        let status = unsafe { sys::da_tree_fit_d(self.handle.raw) };
3083        if status != sys::da_status__da_status_success {
3084            self.handle.note_status(status);
3085            let extra = self.handle.last_error_message().unwrap_or_default();
3086            return Err(Error::Status {
3087                component: "data-analytics",
3088                code: status as i64,
3089                message: format!("tree fit failed: {extra}"),
3090            });
3091        }
3092        Ok(())
3093    }
3094
3095    /// Predict class labels for `n_samples × n_features` test data.
3096    pub fn predict(
3097        &mut self,
3098        n_samples: usize,
3099        n_features: usize,
3100        x_test: &[f64],
3101        labels: &mut [i32],
3102    ) -> Result<()> {
3103        if x_test.len() < n_samples * n_features {
3104            return Err(Error::InvalidArgument(format!(
3105                "tree predict: x_test length {} < n_samples·n_features = {}",
3106                x_test.len(),
3107                n_samples * n_features
3108            )));
3109        }
3110        if labels.len() < n_samples {
3111            return Err(Error::InvalidArgument(format!(
3112                "tree predict: labels length {} < n_samples = {n_samples}",
3113                labels.len()
3114            )));
3115        }
3116        let mut out = IntsOut::new(n_samples);
3117        let status = unsafe {
3118            sys::da_tree_predict_d(
3119                self.handle.raw,
3120                n_samples as sys::da_int,
3121                n_features as sys::da_int,
3122                x_test.as_ptr(),
3123                n_samples as sys::da_int,
3124                out.as_mut_ptr(),
3125            )
3126        };
3127        check_status("data-analytics", status)?;
3128        out.write_back(labels, n_samples)
3129    }
3130
3131    /// Compute prediction accuracy on a labelled test set: returns the
3132    /// fraction of correctly classified samples.
3133    pub fn score(
3134        &mut self,
3135        n_samples: usize,
3136        n_features: usize,
3137        x_test: &[f64],
3138        y_test: &[i32],
3139    ) -> Result<f64> {
3140        check_dense(
3141            "score",
3142            "x_test",
3143            Layout::ColMajor,
3144            n_samples,
3145            n_features,
3146            n_samples,
3147            x_test.len(),
3148        )?;
3149        if y_test.len() < n_samples {
3150            return Err(Error::InvalidArgument(format!(
3151                "score: y_test length {} < n_samples = {n_samples}",
3152                y_test.len()
3153            )));
3154        }
3155        let y_da = ints_in(&y_test[..n_samples]);
3156        let mut acc = 0.0_f64;
3157        let status = unsafe {
3158            sys::da_tree_score_d(
3159                self.handle.raw,
3160                n_samples as sys::da_int,
3161                n_features as sys::da_int,
3162                x_test.as_ptr(),
3163                n_samples as sys::da_int,
3164                y_da.as_ptr(),
3165                &mut acc,
3166            )
3167        };
3168        check_status("data-analytics", status)?;
3169        Ok(acc)
3170    }
3171
3172    /// Predict class probabilities for `n_samples × n_features` test
3173    /// data. `y_proba` is `n_samples × n_class` in the handle's storage
3174    /// order (column-major, as for the features): element (sample `i`,
3175    /// class `c`) is at `c * ldy + i` with `ldy` ≥ `n_samples`.
3176    pub fn predict_proba(
3177        &mut self,
3178        n_samples: usize,
3179        n_features: usize,
3180        x_test: &[f64],
3181        y_proba: &mut [f64],
3182        n_class: usize,
3183        ldy: usize,
3184    ) -> Result<()> {
3185        check_dense(
3186            "predict_proba",
3187            "x_test",
3188            Layout::ColMajor,
3189            n_samples,
3190            n_features,
3191            n_samples,
3192            x_test.len(),
3193        )?;
3194        check_dense(
3195            "predict_proba",
3196            "y_proba",
3197            Layout::ColMajor,
3198            n_samples,
3199            n_class,
3200            ldy,
3201            y_proba.len(),
3202        )?;
3203        let status = unsafe {
3204            sys::da_tree_predict_proba_d(
3205                self.handle.raw,
3206                n_samples as sys::da_int,
3207                n_features as sys::da_int,
3208                x_test.as_ptr(),
3209                n_samples as sys::da_int,
3210                y_proba.as_mut_ptr(),
3211                n_class as sys::da_int,
3212                ldy as sys::da_int,
3213            )
3214        };
3215        check_status("data-analytics", status)
3216    }
3217
3218    /// Predict log class probabilities. See [`DecisionTree::predict_proba`].
3219    pub fn predict_log_proba(
3220        &mut self,
3221        n_samples: usize,
3222        n_features: usize,
3223        x_test: &[f64],
3224        y_log_proba: &mut [f64],
3225        n_class: usize,
3226        ldy: usize,
3227    ) -> Result<()> {
3228        check_dense(
3229            "predict_log_proba",
3230            "x_test",
3231            Layout::ColMajor,
3232            n_samples,
3233            n_features,
3234            n_samples,
3235            x_test.len(),
3236        )?;
3237        check_dense(
3238            "predict_log_proba",
3239            "y_log_proba",
3240            Layout::ColMajor,
3241            n_samples,
3242            n_class,
3243            ldy,
3244            y_log_proba.len(),
3245        )?;
3246        let status = unsafe {
3247            sys::da_tree_predict_log_proba_d(
3248                self.handle.raw,
3249                n_samples as sys::da_int,
3250                n_features as sys::da_int,
3251                x_test.as_ptr(),
3252                n_samples as sys::da_int,
3253                y_log_proba.as_mut_ptr(),
3254                n_class as sys::da_int,
3255                ldy as sys::da_int,
3256            )
3257        };
3258        check_status("data-analytics", status)
3259    }
3260}
3261
3262impl std::fmt::Debug for DecisionTree {
3263    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3264        f.debug_struct("DecisionTree")
3265            .field("handle", &self.handle)
3266            .finish()
3267    }
3268}
3269
3270/// A random-forest classifier. Configure forest options such as
3271/// `"number of trees"` or `"bootstrap"` via [`DecisionForest::handle_mut`]
3272/// before calling [`DecisionForest::fit`].
3273pub struct DecisionForest {
3274    handle: Handle,
3275}
3276
3277impl DecisionForest {
3278    /// Build a new decision-forest handle in `f64` precision.
3279    pub fn new() -> Result<Self> {
3280        let handle = Handle::new_double(HandleKind::DecisionForest)?;
3281        Ok(Self { handle })
3282    }
3283
3284    /// Borrow the underlying handle to set forest options.
3285    pub fn handle_mut(&mut self) -> &mut Handle {
3286        &mut self.handle
3287    }
3288
3289    /// Fit on column-major `n_samples × n_features` features `x` with
3290    /// integer class labels `y`. Pass `n_class = 0` to let AOCL infer it.
3291    pub fn fit(
3292        &mut self,
3293        n_samples: usize,
3294        n_features: usize,
3295        n_class: usize,
3296        x: &[f64],
3297        y: &[i32],
3298    ) -> Result<()> {
3299        if x.len() < n_samples * n_features {
3300            return Err(Error::InvalidArgument(format!(
3301                "forest fit: x length {} < n_samples·n_features = {}",
3302                x.len(),
3303                n_samples * n_features
3304            )));
3305        }
3306        if y.len() < n_samples {
3307            return Err(Error::InvalidArgument(format!(
3308                "forest fit: y length {} < n_samples = {n_samples}",
3309                y.len()
3310            )));
3311        }
3312        let lda = n_samples;
3313        let y_da = ints_in(&y[..n_samples]);
3314        let status = unsafe {
3315            sys::da_forest_set_training_data_d(
3316                self.handle.raw,
3317                n_samples as sys::da_int,
3318                n_features as sys::da_int,
3319                n_class as sys::da_int,
3320                x.as_ptr(),
3321                lda as sys::da_int,
3322                y_da.as_ptr(),
3323                std::ptr::null(), // categorical_features: none (argument added in AOCL 5.3)
3324            )
3325        };
3326        if status != sys::da_status__da_status_success {
3327            self.handle.note_status(status);
3328            let extra = self.handle.last_error_message().unwrap_or_default();
3329            return Err(Error::Status {
3330                component: "data-analytics",
3331                code: status as i64,
3332                message: format!("forest set_training_data failed: {extra}"),
3333            });
3334        }
3335        let status = unsafe { sys::da_forest_fit_d(self.handle.raw) };
3336        if status != sys::da_status__da_status_success {
3337            self.handle.note_status(status);
3338            let extra = self.handle.last_error_message().unwrap_or_default();
3339            return Err(Error::Status {
3340                component: "data-analytics",
3341                code: status as i64,
3342                message: format!("forest fit failed: {extra}"),
3343            });
3344        }
3345        Ok(())
3346    }
3347
3348    /// Predict class labels for `n_samples × n_features` test data.
3349    pub fn predict(
3350        &mut self,
3351        n_samples: usize,
3352        n_features: usize,
3353        x_test: &[f64],
3354        labels: &mut [i32],
3355    ) -> Result<()> {
3356        if x_test.len() < n_samples * n_features {
3357            return Err(Error::InvalidArgument(format!(
3358                "forest predict: x_test length {} < n_samples·n_features = {}",
3359                x_test.len(),
3360                n_samples * n_features
3361            )));
3362        }
3363        if labels.len() < n_samples {
3364            return Err(Error::InvalidArgument(format!(
3365                "forest predict: labels length {} < n_samples = {n_samples}",
3366                labels.len()
3367            )));
3368        }
3369        let mut out = IntsOut::new(n_samples);
3370        let status = unsafe {
3371            sys::da_forest_predict_d(
3372                self.handle.raw,
3373                n_samples as sys::da_int,
3374                n_features as sys::da_int,
3375                x_test.as_ptr(),
3376                n_samples as sys::da_int,
3377                out.as_mut_ptr(),
3378            )
3379        };
3380        check_status("data-analytics", status)?;
3381        out.write_back(labels, n_samples)
3382    }
3383
3384    /// Compute prediction accuracy on a labelled test set.
3385    pub fn score(
3386        &mut self,
3387        n_samples: usize,
3388        n_features: usize,
3389        x_test: &[f64],
3390        y_test: &[i32],
3391    ) -> Result<f64> {
3392        check_dense(
3393            "score",
3394            "x_test",
3395            Layout::ColMajor,
3396            n_samples,
3397            n_features,
3398            n_samples,
3399            x_test.len(),
3400        )?;
3401        if y_test.len() < n_samples {
3402            return Err(Error::InvalidArgument(format!(
3403                "score: y_test length {} < n_samples = {n_samples}",
3404                y_test.len()
3405            )));
3406        }
3407        let y_da = ints_in(&y_test[..n_samples]);
3408        let mut acc = 0.0_f64;
3409        let status = unsafe {
3410            sys::da_forest_score_d(
3411                self.handle.raw,
3412                n_samples as sys::da_int,
3413                n_features as sys::da_int,
3414                x_test.as_ptr(),
3415                n_samples as sys::da_int,
3416                y_da.as_ptr(),
3417                &mut acc,
3418            )
3419        };
3420        check_status("data-analytics", status)?;
3421        Ok(acc)
3422    }
3423
3424    /// Predict class probabilities for the random forest. See
3425    /// [`DecisionTree::predict_proba`].
3426    pub fn predict_proba(
3427        &mut self,
3428        n_samples: usize,
3429        n_features: usize,
3430        x_test: &[f64],
3431        y_proba: &mut [f64],
3432        n_class: usize,
3433        ldy: usize,
3434    ) -> Result<()> {
3435        check_dense(
3436            "predict_proba",
3437            "x_test",
3438            Layout::ColMajor,
3439            n_samples,
3440            n_features,
3441            n_samples,
3442            x_test.len(),
3443        )?;
3444        check_dense(
3445            "predict_proba",
3446            "y_proba",
3447            Layout::ColMajor,
3448            n_samples,
3449            n_class,
3450            ldy,
3451            y_proba.len(),
3452        )?;
3453        let status = unsafe {
3454            sys::da_forest_predict_proba_d(
3455                self.handle.raw,
3456                n_samples as sys::da_int,
3457                n_features as sys::da_int,
3458                x_test.as_ptr(),
3459                n_samples as sys::da_int,
3460                y_proba.as_mut_ptr(),
3461                n_class as sys::da_int,
3462                ldy as sys::da_int,
3463            )
3464        };
3465        check_status("data-analytics", status)
3466    }
3467
3468    /// Predict log class probabilities for the random forest.
3469    pub fn predict_log_proba(
3470        &mut self,
3471        n_samples: usize,
3472        n_features: usize,
3473        x_test: &[f64],
3474        y_log_proba: &mut [f64],
3475        n_class: usize,
3476        ldy: usize,
3477    ) -> Result<()> {
3478        check_dense(
3479            "predict_log_proba",
3480            "x_test",
3481            Layout::ColMajor,
3482            n_samples,
3483            n_features,
3484            n_samples,
3485            x_test.len(),
3486        )?;
3487        check_dense(
3488            "predict_log_proba",
3489            "y_log_proba",
3490            Layout::ColMajor,
3491            n_samples,
3492            n_class,
3493            ldy,
3494            y_log_proba.len(),
3495        )?;
3496        let status = unsafe {
3497            sys::da_forest_predict_log_proba_d(
3498                self.handle.raw,
3499                n_samples as sys::da_int,
3500                n_features as sys::da_int,
3501                x_test.as_ptr(),
3502                n_samples as sys::da_int,
3503                y_log_proba.as_mut_ptr(),
3504                n_class as sys::da_int,
3505                ldy as sys::da_int,
3506            )
3507        };
3508        check_status("data-analytics", status)
3509    }
3510}
3511
3512impl std::fmt::Debug for DecisionForest {
3513    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3514        f.debug_struct("DecisionForest")
3515            .field("handle", &self.handle)
3516            .finish()
3517    }
3518}
3519
3520// =========================================================================
3521//   Support Vector Machines (SVM)
3522// =========================================================================
3523
3524/// Family of SVM model. Classification variants train against integer
3525/// class labels (passed as `f64`); regression variants train against a
3526/// real-valued response.
3527#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3528#[non_exhaustive]
3529pub enum SvmKind {
3530    /// C-regularised classification (`SVC`).
3531    Svc,
3532    /// Nu-regularised classification (`NuSVC`).
3533    NuSvc,
3534    /// Epsilon-regularised regression (`SVR`).
3535    Svr,
3536    /// Nu-regularised regression (`NuSVR`).
3537    NuSvr,
3538}
3539
3540impl SvmKind {
3541    fn raw(self) -> sys::da_svm_model {
3542        match self {
3543            SvmKind::Svc => sys::da_svm_model__svc,
3544            SvmKind::NuSvc => sys::da_svm_model__nusvc,
3545            SvmKind::Svr => sys::da_svm_model__svr,
3546            SvmKind::NuSvr => sys::da_svm_model__nusvr,
3547        }
3548    }
3549}
3550
3551/// Decision-function shape used for multi-class classification.
3552#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
3553pub enum DecisionShape {
3554    /// One-vs-Rest.
3555    Ovr,
3556    /// One-vs-One.
3557    Ovo,
3558}
3559
3560impl DecisionShape {
3561    fn raw(self) -> sys::da_svm_decision_function_shape {
3562        match self {
3563            DecisionShape::Ovr => sys::da_svm_decision_function_shape__ovr,
3564            DecisionShape::Ovo => sys::da_svm_decision_function_shape__ovo,
3565        }
3566    }
3567}
3568
3569/// Support vector machine wrapper covering both classification (`Svc`,
3570/// `NuSvc`) and regression (`Svr`, `NuSvr`) modes. Configure
3571/// SVM-specific options (kernel, C, epsilon, gamma, …) via
3572/// [`Svm::handle_mut`] before calling [`Svm::fit`].
3573pub struct Svm {
3574    handle: Handle,
3575    kind: SvmKind,
3576    /// Number of distinct labels seen by `fit` (0 before a fit; classification models only), for the decision-function size.
3577    n_class: usize,
3578}
3579
3580impl Svm {
3581    /// Build a C-SVC classifier in `f64` precision.
3582    pub fn new_svc() -> Result<Self> {
3583        Self::new_with(SvmKind::Svc)
3584    }
3585    /// Build a Nu-SVC classifier in `f64` precision.
3586    pub fn new_nu_svc() -> Result<Self> {
3587        Self::new_with(SvmKind::NuSvc)
3588    }
3589    /// Build an epsilon-SVR regressor in `f64` precision.
3590    pub fn new_svr() -> Result<Self> {
3591        Self::new_with(SvmKind::Svr)
3592    }
3593    /// Build a Nu-SVR regressor in `f64` precision.
3594    pub fn new_nu_svr() -> Result<Self> {
3595        Self::new_with(SvmKind::NuSvr)
3596    }
3597
3598    fn new_with(kind: SvmKind) -> Result<Self> {
3599        let handle = Handle::new_double(HandleKind::Svm)?;
3600        let status = unsafe { sys::da_svm_select_model_d(handle.raw, kind.raw()) };
3601        check_status("data-analytics", status)?;
3602        Ok(Self {
3603            handle,
3604            kind,
3605            n_class: 0,
3606        })
3607    }
3608
3609    /// Borrow the underlying handle to set SVM-specific options.
3610    pub fn handle_mut(&mut self) -> &mut Handle {
3611        &mut self.handle
3612    }
3613
3614    /// Family of SVM model that this handle was constructed for.
3615    pub fn kind(&self) -> SvmKind {
3616        self.kind
3617    }
3618
3619    /// Fit on column-major `n_samples × n_features` features `x` and a
3620    /// length-`n_samples` response vector `y`. For classification, `y`
3621    /// holds class indices `0..n_class-1` (as floats); for regression
3622    /// it holds the real target.
3623    pub fn fit(&mut self, n_samples: usize, n_features: usize, x: &[f64], y: &[f64]) -> Result<()> {
3624        if x.len() < n_samples * n_features {
3625            return Err(Error::InvalidArgument(format!(
3626                "svm fit: x length {} < n_samples·n_features = {}",
3627                x.len(),
3628                n_samples * n_features
3629            )));
3630        }
3631        if y.len() < n_samples {
3632            return Err(Error::InvalidArgument(format!(
3633                "svm fit: y length {} < n_samples = {n_samples}",
3634                y.len()
3635            )));
3636        }
3637        if matches!(self.kind, SvmKind::Svc | SvmKind::NuSvc) {
3638            let mut c: Vec<i64> = y[..n_samples].iter().map(|v| *v as i64).collect();
3639            c.sort_unstable();
3640            c.dedup();
3641            self.n_class = c.len();
3642        }
3643        let lda = n_samples;
3644        let status = unsafe {
3645            sys::da_svm_set_data_d(
3646                self.handle.raw,
3647                n_samples as sys::da_int,
3648                n_features as sys::da_int,
3649                x.as_ptr(),
3650                lda as sys::da_int,
3651                y.as_ptr(),
3652            )
3653        };
3654        if status != sys::da_status__da_status_success {
3655            self.handle.note_status(status);
3656            let extra = self.handle.last_error_message().unwrap_or_default();
3657            return Err(Error::Status {
3658                component: "data-analytics",
3659                code: status as i64,
3660                message: format!("svm set_data failed: {extra}"),
3661            });
3662        }
3663        let status = unsafe { sys::da_svm_compute_d(self.handle.raw) };
3664        if status != sys::da_status__da_status_success {
3665            self.handle.note_status(status);
3666            let extra = self.handle.last_error_message().unwrap_or_default();
3667            return Err(Error::Status {
3668                component: "data-analytics",
3669                code: status as i64,
3670                message: format!("svm compute failed: {extra}"),
3671            });
3672        }
3673        Ok(())
3674    }
3675
3676    /// Predict labels (classification) or values (regression) for new
3677    /// data. `predictions` receives `n_samples` outputs.
3678    pub fn predict(
3679        &mut self,
3680        n_samples: usize,
3681        n_features: usize,
3682        x_test: &[f64],
3683        predictions: &mut [f64],
3684    ) -> Result<()> {
3685        if x_test.len() < n_samples * n_features {
3686            return Err(Error::InvalidArgument(format!(
3687                "svm predict: x_test length {} < n_samples·n_features = {}",
3688                x_test.len(),
3689                n_samples * n_features
3690            )));
3691        }
3692        if predictions.len() < n_samples {
3693            return Err(Error::InvalidArgument(format!(
3694                "svm predict: predictions length {} < n_samples = {n_samples}",
3695                predictions.len()
3696            )));
3697        }
3698        let status = unsafe {
3699            sys::da_svm_predict_d(
3700                self.handle.raw,
3701                n_samples as sys::da_int,
3702                n_features as sys::da_int,
3703                x_test.as_ptr(),
3704                n_samples as sys::da_int,
3705                predictions.as_mut_ptr(),
3706            )
3707        };
3708        check_status("data-analytics", status)
3709    }
3710
3711    /// Compute the model's score: accuracy for classification or `R²`
3712    /// for regression.
3713    pub fn score(
3714        &mut self,
3715        n_samples: usize,
3716        n_features: usize,
3717        x_test: &[f64],
3718        y_test: &[f64],
3719    ) -> Result<f64> {
3720        check_dense(
3721            "svm score",
3722            "x_test",
3723            Layout::ColMajor,
3724            n_samples,
3725            n_features,
3726            n_samples,
3727            x_test.len(),
3728        )?;
3729        if y_test.len() < n_samples {
3730            return Err(Error::InvalidArgument(format!(
3731                "svm score: y_test has {} elements, {n_samples} are needed",
3732                y_test.len()
3733            )));
3734        }
3735        let mut s = 0.0_f64;
3736        let status = unsafe {
3737            sys::da_svm_score_d(
3738                self.handle.raw,
3739                n_samples as sys::da_int,
3740                n_features as sys::da_int,
3741                x_test.as_ptr(),
3742                n_samples as sys::da_int,
3743                y_test.as_ptr(),
3744                &mut s,
3745            )
3746        };
3747        check_status("data-analytics", status)?;
3748        Ok(s)
3749    }
3750
3751    /// Compute the SVM decision function on test data (classification
3752    /// only; for regression call [`Svm::predict`] directly). Output
3753    /// layout depends on `shape` and `n_class`; see AOCL docs for the
3754    /// exact size requirements.
3755    pub fn decision_function(
3756        &mut self,
3757        n_samples: usize,
3758        n_features: usize,
3759        x_test: &[f64],
3760        shape: DecisionShape,
3761        decision_values: &mut [f64],
3762        ldd: usize,
3763    ) -> Result<()> {
3764        check_dense(
3765            "decision_function",
3766            "x_test",
3767            Layout::ColMajor,
3768            n_samples,
3769            n_features,
3770            n_samples,
3771            x_test.len(),
3772        )?;
3773        // 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
3774        let cols = if self.n_class <= 2 {
3775            1
3776        } else {
3777            match shape {
3778                DecisionShape::Ovo => self.n_class * (self.n_class - 1) / 2,
3779                DecisionShape::Ovr => self.n_class,
3780            }
3781        };
3782        check_dense(
3783            "decision_function",
3784            "decision_values",
3785            Layout::ColMajor,
3786            n_samples,
3787            cols,
3788            ldd,
3789            decision_values.len(),
3790        )?;
3791        let status = unsafe {
3792            sys::da_svm_decision_function_d(
3793                self.handle.raw,
3794                n_samples as sys::da_int,
3795                n_features as sys::da_int,
3796                x_test.as_ptr(),
3797                n_samples as sys::da_int,
3798                shape.raw(),
3799                decision_values.as_mut_ptr(),
3800                ldd as sys::da_int,
3801            )
3802        };
3803        check_status("data-analytics", status)
3804    }
3805}
3806
3807impl std::fmt::Debug for Svm {
3808    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3809        f.debug_struct("Svm")
3810            .field("kind", &self.kind)
3811            .field("handle", &self.handle)
3812            .finish()
3813    }
3814}
3815
3816#[cfg(test)]
3817mod tests {
3818    use super::*;
3819
3820    #[test]
3821    fn column_means_2x3() {
3822        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0];
3823        let mut out = [0.0_f64; 3];
3824        mean(Axis::Col, 2, 3, &x, &mut out).unwrap();
3825        assert!((out[0] - 2.5).abs() < 1e-12);
3826        assert!((out[1] - 3.5).abs() < 1e-12);
3827        assert!((out[2] - 4.5).abs() < 1e-12);
3828    }
3829
3830    #[test]
3831    fn row_means_2x3() {
3832        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0];
3833        let mut out = [0.0_f64; 2];
3834        mean(Axis::Row, 2, 3, &x, &mut out).unwrap();
3835        assert!((out[0] - 2.0).abs() < 1e-12);
3836        assert!((out[1] - 5.0).abs() < 1e-12);
3837    }
3838
3839    #[test]
3840    fn variance_dof_conventions() {
3841        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
3842        let mut mu = [0.0_f64; 1];
3843        let mut var = [0.0_f64; 1];
3844
3845        variance(Axis::All, 1, 5, &x, -1, &mut mu, &mut var).unwrap();
3846        assert!((mu[0] - 3.0).abs() < 1e-12);
3847        assert!((var[0] - 2.0).abs() < 1e-12, "n-divisor var = {}", var[0]);
3848
3849        variance(Axis::All, 1, 5, &x, 0, &mut mu, &mut var).unwrap();
3850        assert!(
3851            (var[0] - 2.5).abs() < 1e-12,
3852            "(n-1)-divisor var = {}",
3853            var[0]
3854        );
3855
3856        variance(Axis::All, 1, 5, &x, 2, &mut mu, &mut var).unwrap();
3857        assert!(
3858            (var[0] - 5.0).abs() < 1e-12,
3859            "literal-divisor var = {}",
3860            var[0]
3861        );
3862    }
3863
3864    #[test]
3865    fn dim_mismatch_is_error() {
3866        let x = [1.0_f64; 4];
3867        let mut out = [0.0_f64; 3];
3868        let err = mean(Axis::Col, 2, 3, &x, &mut out).unwrap_err();
3869        matches!(err, Error::InvalidArgument(_));
3870    }
3871
3872    #[test]
3873    fn handle_init_destroy() {
3874        // Smoke test: handle creation + drop on each algorithm kind.
3875        let _h1 = Handle::new_double(HandleKind::Kmeans).unwrap();
3876        let _h2 = Handle::new_double(HandleKind::Pca).unwrap();
3877        let _h3 = Handle::new_single(HandleKind::Linmod).unwrap();
3878    }
3879
3880    #[test]
3881    fn pca_two_components() {
3882        // 4 points in 3-D forming a clear 2-D plane: x and y vary,
3883        // z is small noise.
3884        // Stored column-major (column = feature).
3885        let data: Vec<f64> = vec![
3886            // feature 0 (x): values 1, 2, 3, 4
3887            1.0, 2.0, 3.0, 4.0, // feature 1 (y): values 4, 3, 2, 1
3888            4.0, 3.0, 2.0, 1.0, // feature 2 (z): tiny noise
3889            0.01, 0.02, 0.01, 0.02,
3890        ];
3891        let mut pca = Pca::new(2).unwrap();
3892        pca.fit(4, 3, &data).unwrap();
3893
3894        let mut transformed = vec![0.0_f64; 4 * 2];
3895        pca.transform(4, 3, &data, 2, &mut transformed).unwrap();
3896        // First two PCs should capture nearly all the variance — the
3897        // transformed values should be non-trivial (not all zero).
3898        let nonzero = transformed.iter().any(|&v| v.abs() > 1e-6);
3899        assert!(nonzero, "PCA-transformed coordinates were all zero");
3900    }
3901
3902    #[test]
3903    fn knn_two_class_separation() {
3904        // Two clusters in 2-D (column-major): label 0 around (0,0),
3905        // label 1 around (10,10).
3906        let x_train: Vec<f64> = vec![
3907            // feature 0
3908            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, // feature 1
3909            0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
3910        ];
3911        let y_train = vec![0_i32, 0, 0, 1, 1, 1];
3912        let mut knn = KNearestNeighbours::new().unwrap();
3913        knn.fit(6, 2, &x_train, &y_train).unwrap();
3914
3915        // A query point near (0, 0) → label 0; near (10, 10) → label 1.
3916        let x_test = vec![
3917            0.05, 9.95, // feature 0
3918            0.05, 10.05, // feature 1
3919        ];
3920        let mut labels = vec![0_i32; 2];
3921        knn.predict(2, 2, &x_test, &mut labels).unwrap();
3922        assert_eq!(labels[0], 0);
3923        assert_eq!(labels[1], 1);
3924    }
3925
3926    #[test]
3927    fn decision_tree_two_class_separation() {
3928        // Same separable two-class setup as the KNN test.
3929        let x_train: Vec<f64> = vec![
3930            // feature 0
3931            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, // feature 1
3932            0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
3933        ];
3934        let y_train = vec![0_i32, 0, 0, 1, 1, 1];
3935        let mut tree = DecisionTree::new().unwrap();
3936        tree.fit(6, 2, 2, &x_train, &y_train).unwrap();
3937
3938        let x_test = vec![0.05, 9.95, 0.05, 10.05];
3939        let mut labels = vec![0_i32; 2];
3940        tree.predict(2, 2, &x_test, &mut labels).unwrap();
3941        assert_eq!(labels[0], 0);
3942        assert_eq!(labels[1], 1);
3943
3944        // Score on the training set should be 1.0 for this separable problem.
3945        let acc = tree.score(6, 2, &x_train, &y_train).unwrap();
3946        assert!((acc - 1.0).abs() < 1e-9, "score = {acc}");
3947    }
3948
3949    #[test]
3950    fn decision_forest_two_class_separation() {
3951        let x_train: Vec<f64> = vec![
3952            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, 0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
3953        ];
3954        let y_train = vec![0_i32, 0, 0, 1, 1, 1];
3955        let mut forest = DecisionForest::new().unwrap();
3956        forest.fit(6, 2, 2, &x_train, &y_train).unwrap();
3957
3958        let x_test = vec![0.05, 9.95, 0.05, 10.05];
3959        let mut labels = vec![0_i32; 2];
3960        forest.predict(2, 2, &x_test, &mut labels).unwrap();
3961        assert_eq!(labels[0], 0);
3962        assert_eq!(labels[1], 1);
3963
3964        let acc = forest.score(6, 2, &x_train, &y_train).unwrap();
3965        assert!((acc - 1.0).abs() < 1e-9, "score = {acc}");
3966    }
3967
3968    #[test]
3969    fn datastore_init_destroy_and_options() {
3970        let mut store = Datastore::new().unwrap();
3971        // Setting a few standard options should succeed even on an
3972        // empty store.
3973        store.set_int_option("use header row", 1).unwrap();
3974        store.set_int_option("whitespace delimiter", 1).unwrap();
3975        store.set_string_option("comment", "#").unwrap();
3976        // dims() should report (0, 0) before any data is loaded.
3977        let (r, c) = store.dims().unwrap();
3978        assert_eq!((r, c), (0, 0));
3979    }
3980
3981    #[test]
3982    fn datastore_round_trip_through_temp_csv() {
3983        // Write a minimal numeric CSV to a tempfile, load it via the
3984        // datastore, select all columns, and extract.
3985        use std::io::Write;
3986        let mut path = std::env::temp_dir();
3987        path.push(format!("aocl_da_csv_{}.csv", std::process::id()));
3988        {
3989            let mut f = std::fs::File::create(&path).unwrap();
3990            // 3 rows × 2 cols; no header.
3991            writeln!(f, "1.0,2.0").unwrap();
3992            writeln!(f, "3.0,4.0").unwrap();
3993            writeln!(f, "5.0,6.0").unwrap();
3994        }
3995
3996        let mut store = Datastore::new().unwrap();
3997        store.load_csv(path.to_str().unwrap()).unwrap();
3998        let (r, c) = store.dims().unwrap();
3999        assert_eq!((r, c), (3, 2));
4000
4001        store.select_columns("all", 0, 1).unwrap();
4002        let mut buf = vec![0.0_f64; 6];
4003        // Column-major layout, lddata = n_rows.
4004        store
4005            .extract_f64("all", Layout::ColMajor, &mut buf, 3)
4006            .unwrap();
4007        // Column 0 = [1, 3, 5]; column 1 = [2, 4, 6].
4008        assert!((buf[0] - 1.0).abs() < 1e-12);
4009        assert!((buf[1] - 3.0).abs() < 1e-12);
4010        assert!((buf[2] - 5.0).abs() < 1e-12);
4011        assert!((buf[3] - 2.0).abs() < 1e-12);
4012        assert!((buf[4] - 4.0).abs() < 1e-12);
4013        assert!((buf[5] - 6.0).abs() < 1e-12);
4014
4015        let _ = std::fs::remove_file(&path);
4016    }
4017
4018    /// Red-first, SAFE code only: several threads each build and fit their own `Nlls` through the safe API. RALFit in
4019    /// `aocl-da.dll` is not safe to run concurrently (AOCL 6.0.68, Windows: the process died with an access violation
4020    /// before the wrapper serialised the NLLS library calls). Each thread must recover its own parameters.
4021    #[test]
4022    fn concurrent_nlls_fits_through_the_safe_api_do_not_crash() {
4023        let threads: Vec<_> = (0..6)
4024            .map(|k| {
4025                std::thread::spawn(move || {
4026                    for rep in 0..15 {
4027                        let t: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0];
4028                        let (a, b) = (1.0 + k as f64 * 0.5, 0.2 + 0.05 * rep as f64);
4029                        let y: Vec<f64> = t.iter().map(|&ti| a * (-b * ti).exp()).collect();
4030                        let resfun = move |x: &[f64], res: &mut [f64]| -> i32 {
4031                            for i in 0..res.len() {
4032                                res[i] = x[0] * (-x[1] * t[i]).exp() - y[i];
4033                            }
4034                            0
4035                        };
4036                        let mut m = Nlls::new(2, 5, resfun).unwrap();
4037                        let mut coef = vec![1.0_f64, 1.0_f64];
4038                        m.fit(&mut coef).unwrap();
4039                        assert!(
4040                            (coef[0] - a).abs() < 1e-3 && (coef[1] - b).abs() < 1e-3,
4041                            "thread {k} rep {rep}: {coef:?} vs ({a}, {b})"
4042                        );
4043                    }
4044                })
4045            })
4046            .collect();
4047        for h in threads {
4048            h.join().unwrap();
4049        }
4050    }
4051
4052    #[test]
4053    fn nlls_fits_exponential_decay() {
4054        // Fit y(t) = a · exp(-b · t) to noiseless data with a=2, b=0.3.
4055        // 5 sample points; residuals = predictions - observed.
4056        let t: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0];
4057        let true_a = 2.0_f64;
4058        let true_b = 0.3_f64;
4059        let y: Vec<f64> = t.iter().map(|&ti| true_a * (-true_b * ti).exp()).collect();
4060
4061        // Closure captures t and y by reference. resfun computes
4062        // r_i(x) = a · exp(-b · t_i) - y_i, where x = [a, b].
4063        let n_coef = 2;
4064        let n_res = t.len();
4065        let resfun = |x: &[f64], res: &mut [f64]| -> i32 {
4066            let a = x[0];
4067            let b = x[1];
4068            for i in 0..res.len() {
4069                res[i] = a * (-b * t[i]).exp() - y[i];
4070            }
4071            0
4072        };
4073
4074        let mut model = Nlls::new(n_coef, n_res, resfun).unwrap();
4075        // Start far from the truth to give the optimiser real work.
4076        let mut coef = vec![1.0_f64, 1.0_f64];
4077        model.fit(&mut coef).unwrap();
4078
4079        // Should recover the true parameters within a tight tolerance.
4080        assert!((coef[0] - true_a).abs() < 1e-4, "a = {}", coef[0]);
4081        assert!((coef[1] - true_b).abs() < 1e-4, "b = {}", coef[1]);
4082
4083        // Solver info should report nonzero iterations.
4084        let rinfo = model.info().unwrap();
4085        assert!(!rinfo.is_empty());
4086        // info[2] is iter count per the C header; should be > 0.
4087        assert!(rinfo[2] > 0.0, "iterations = {}", rinfo[2]);
4088    }
4089
4090    #[test]
4091    fn linear_kernel_self_gram() {
4092        // X = [[1, 0], [0, 1], [1, 1]] row-major; Gram = X·Xᵀ
4093        // = [[1, 0, 1], [0, 1, 1], [1, 1, 2]]
4094        let x = [1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4095        let mut d = [0.0_f64; 9];
4096        linear_kernel::<f64>(3, 0, 2, &x, None, &mut d).unwrap();
4097        let want = [1.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 2.0];
4098        for (got, w) in d.iter().zip(want.iter()) {
4099            assert!((got - w).abs() < 1e-12, "got {got}, want {w}");
4100        }
4101    }
4102
4103    #[test]
4104    fn rbf_kernel_diagonal_is_one() {
4105        // RBF kernel of any vector with itself is exp(0) = 1.
4106        // Two-point set; check the diagonal entries.
4107        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]; // 2 rows × 3 cols
4108        let mut d = [0.0_f64; 4];
4109        rbf_kernel::<f64>(2, 0, 3, &x, None, &mut d, 0.5).unwrap();
4110        // d[0] (= K(x0, x0)) and d[3] (= K(x1, x1)) should be 1.
4111        assert!((d[0] - 1.0).abs() < 1e-12, "K(x0,x0) = {}", d[0]);
4112        assert!((d[3] - 1.0).abs() < 1e-12, "K(x1,x1) = {}", d[3]);
4113        // Off-diagonal should be < 1.
4114        assert!(d[1] < 1.0);
4115        assert!(d[2] < 1.0);
4116    }
4117
4118    #[test]
4119    fn pairwise_distances_within_set() {
4120        // Three 2-D points on the corners of a 3-4-5 right triangle:
4121        // p0 = (0, 0); p1 = (3, 0); p2 = (0, 4)
4122        // Row-major 3×2 matrix.
4123        let x = [0.0_f64, 0.0, 3.0, 0.0, 0.0, 4.0];
4124        let mut d = [0.0_f64; 9];
4125        pairwise_distances::<f64>(3, 0, 2, &x, None, &mut d, 2.0, Metric::Euclidean).unwrap();
4126        // d is 3×3 row-major; diagonal = 0, off-diagonals are 3, 4, 5.
4127        assert!(d[0].abs() < 1e-12);
4128        assert!((d[1] - 3.0).abs() < 1e-9, "d[0,1] = {}", d[1]);
4129        assert!((d[2] - 4.0).abs() < 1e-9, "d[0,2] = {}", d[2]);
4130        assert!((d[3] - 3.0).abs() < 1e-9);
4131        assert!(d[4].abs() < 1e-12);
4132        assert!((d[5] - 5.0).abs() < 1e-9, "d[1,2] = {}", d[5]);
4133    }
4134
4135    #[test]
4136    fn quantile_median_of_1_to_5() {
4137        // Row-major 1×5 row vector; median (q=0.5) should be 3.
4138        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
4139        let mut q = [0.0_f64; 1];
4140        quantile(Axis::All, 1, 5, &x, 0.5, &mut q, QuantileType::Type7).unwrap();
4141        assert!((q[0] - 3.0).abs() < 1e-12, "median = {}", q[0]);
4142    }
4143
4144    #[test]
4145    fn five_point_summary_works() {
4146        // 1×5 row vector — five-number summary should give 1, ?, 3, ?, 5.
4147        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
4148        let mut min = [0.0_f64; 1];
4149        let mut lower = [0.0_f64; 1];
4150        let mut med = [0.0_f64; 1];
4151        let mut upper = [0.0_f64; 1];
4152        let mut max = [0.0_f64; 1];
4153        five_point_summary(
4154            Axis::All,
4155            1,
4156            5,
4157            &x,
4158            &mut min,
4159            &mut lower,
4160            &mut med,
4161            &mut upper,
4162            &mut max,
4163        )
4164        .unwrap();
4165        assert!((min[0] - 1.0).abs() < 1e-12);
4166        assert!((max[0] - 5.0).abs() < 1e-12);
4167        assert!((med[0] - 3.0).abs() < 1e-12);
4168        // Hinges should sit between min and median, median and max.
4169        assert!(lower[0] >= min[0] && lower[0] <= med[0]);
4170        assert!(upper[0] >= med[0] && upper[0] <= max[0]);
4171    }
4172
4173    /// 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
4174    /// are 5/3 and the covariance is 1. If the data were wrongly treated as already centred (AOCL 5.3's
4175    /// `assume_centered = 1`) the diagonal would be 10 and the off-diagonal 11/3 instead.
4176    #[test]
4177    fn covariance_matrix_subtracts_column_means() {
4178        let x = [1.0_f64, 2.0, 2.0, 1.0, 3.0, 4.0, 4.0, 3.0];
4179        let mut cov = [0.0_f64; 4];
4180        covariance_matrix(4, 2, &x, 0, &mut cov).unwrap();
4181        let want = [5.0 / 3.0, 1.0, 1.0, 5.0 / 3.0];
4182        for (g, w) in cov.iter().zip(want) {
4183            assert!((g - w).abs() < 1e-12, "cov = {cov:?}, want {want:?}");
4184        }
4185    }
4186
4187    #[test]
4188    fn correlation_matrix_identity_for_perfectly_correlated() {
4189        // Two perfectly correlated columns: y = 2*x + 1. Correlation
4190        // matrix is the 2x2 all-ones matrix.
4191        // Row-major: 4 rows, 2 columns.
4192        let x = [1.0_f64, 3.0, 2.0, 5.0, 3.0, 7.0, 4.0, 9.0];
4193        let mut corr = [0.0_f64; 4];
4194        correlation_matrix(4, 2, &x, &mut corr).unwrap();
4195        for v in &corr {
4196            assert!((v - 1.0).abs() < 1e-9, "off-diagonal correlation = {}", v);
4197        }
4198    }
4199
4200    #[test]
4201    fn skewness_kurtosis_normal_data_near_zero() {
4202        // Symmetric data → skewness ≈ 0; mesokurtic ≈ 0 (Fisher).
4203        let x = [1.0_f64, 2.0, 3.0, 4.0, 5.0]; // 1×5 row vector
4204        let mut mu = [0.0_f64; 1];
4205        let mut var = [0.0_f64; 1];
4206        let mut skew = [0.0_f64; 1];
4207        skewness(Axis::All, 1, 5, &x, &mut mu, &mut var, &mut skew).unwrap();
4208        assert!((mu[0] - 3.0).abs() < 1e-12);
4209        assert!(skew[0].abs() < 1e-9, "skewness = {}", skew[0]);
4210
4211        let mut kurt = [0.0_f64; 1];
4212        kurtosis(Axis::All, 1, 5, &x, &mut mu, &mut var, &mut kurt).unwrap();
4213        // Uniform discrete sample like 1..5 has Fisher kurtosis = -1.3.
4214        assert!(kurt[0] < 0.0, "kurtosis = {}", kurt[0]);
4215    }
4216
4217    #[test]
4218    fn svm_svc_two_class_separation() {
4219        // Same separable two-class setup; SVM uses f64 labels (class
4220        // indices stored as floats).
4221        let x_train: Vec<f64> = vec![
4222            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, 0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
4223        ];
4224        let y_train = vec![0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4225        let mut svm = Svm::new_svc().unwrap();
4226        svm.fit(6, 2, &x_train, &y_train).unwrap();
4227
4228        let x_test = vec![0.05, 9.95, 0.05, 10.05];
4229        let mut predictions = vec![0.0_f64; 2];
4230        svm.predict(2, 2, &x_test, &mut predictions).unwrap();
4231        assert!(
4232            (predictions[0] - 0.0).abs() < 1e-9,
4233            "pred[0] = {}",
4234            predictions[0]
4235        );
4236        assert!(
4237            (predictions[1] - 1.0).abs() < 1e-9,
4238            "pred[1] = {}",
4239            predictions[1]
4240        );
4241
4242        let acc = svm.score(6, 2, &x_train, &y_train).unwrap();
4243        assert!((acc - 1.0).abs() < 1e-9, "score = {acc}");
4244    }
4245
4246    #[test]
4247    fn dbscan_two_clusters() {
4248        // Two well-separated clusters; should yield n_clusters = 2 and
4249        // each cluster's samples sharing a positive label.
4250        let data: Vec<f64> = vec![
4251            // feature 0 (column 0): cluster A near 0, cluster B near 10
4252            0.0, 0.1, 0.2, 0.0, 0.1, 10.0, 10.1, 10.0, 10.2, 10.1, // feature 1 (column 1)
4253            0.0, 0.1, 0.0, 0.2, 0.1, 10.0, 10.1, 10.2, 10.0, 10.1,
4254        ];
4255        let mut db = Dbscan::new().unwrap();
4256        // Set min_samples small so a 5-point cluster qualifies; eps the
4257        // default (which is ~0.5 in AOCL) is not enough so widen it.
4258        // We use the underlying real-valued setter directly.
4259        let cs = std::ffi::CString::new("eps").unwrap();
4260        let status =
4261            unsafe { sys::da_options_set_real_d(db.handle_mut().as_raw(), cs.as_ptr(), 1.0) };
4262        assert_eq!(status, sys::da_status__da_status_success);
4263        db.handle_mut().set_int_option("min samples", 3).unwrap();
4264        db.fit(10, 2, &data).unwrap();
4265        assert_eq!(db.n_clusters().unwrap(), 2);
4266        let labels = db.labels().unwrap();
4267        // First five samples share a label, last five share another.
4268        assert_eq!(labels[0], labels[1]);
4269        assert_eq!(labels[1], labels[2]);
4270        assert_eq!(labels[5], labels[6]);
4271        assert_eq!(labels[6], labels[9]);
4272        assert_ne!(labels[0], labels[5]);
4273        assert!(db.n_core_samples().unwrap() > 0);
4274    }
4275
4276    #[test]
4277    fn linmod_mse_recovers_linear_relationship() {
4278        // y = 2 * x0 + 3 * x1 + small intercept; one feature varies with
4279        // each axis. Column-major: feature 0 first, then feature 1.
4280        // Use 5 samples to give the solver something to work with.
4281        let x: Vec<f64> = vec![
4282            // feature 0
4283            1.0, 2.0, 3.0, 4.0, 5.0, // feature 1
4284            5.0, 4.0, 3.0, 2.0, 1.0,
4285        ];
4286        // y = 2·x0 + 3·x1 (no noise)
4287        let y: Vec<f64> = vec![17.0, 16.0, 15.0, 14.0, 13.0];
4288        let mut model = Linmod::new_mse().unwrap();
4289        model.fit(5, 2, &x, &y).unwrap();
4290        let coefs = model.coefficients().unwrap();
4291        assert!(!coefs.is_empty(), "fitted coefficients vector was empty");
4292        // The first two entries should approximate the true coefficients.
4293        // AOCL may report them with small floating-point noise.
4294        assert!((coefs[0] - 2.0).abs() < 1e-6, "coef[0] = {}", coefs[0]);
4295        assert!((coefs[1] - 3.0).abs() < 1e-6, "coef[1] = {}", coefs[1]);
4296
4297        // Predict on the same samples — should reproduce y nearly exactly.
4298        let mut pred = vec![0.0_f64; 5];
4299        model.predict(5, 2, &x, &mut pred).unwrap();
4300        for (got, want) in pred.iter().zip(y.iter()) {
4301            assert!((got - want).abs() < 1e-6, "predict {} vs {}", got, want);
4302        }
4303
4304        // evaluate() produces a loss; the loss for an exact fit is small
4305        // (zero up to floating-point noise).
4306        let mut pred2 = vec![0.0_f64; 5];
4307        let loss = model.evaluate(5, 2, &x, &y, &mut pred2).unwrap();
4308        assert!(loss.abs() < 1e-6, "exact-fit loss = {}", loss);
4309    }
4310
4311    #[test]
4312    fn kmeans_two_clusters() {
4313        // Two well-separated clusters: rows 0..=2 near (0, 0); rows
4314        // 3..=5 near (10, 10). Stored column-major: feature 0 first,
4315        // then feature 1.
4316        let data: Vec<f64> = vec![
4317            // feature 0 (column 0)
4318            0.0, 0.1, 0.2, 10.0, 10.1, 10.2, // feature 1 (column 1)
4319            0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
4320        ];
4321        let mut km = KMeans::new(2).unwrap();
4322        km.fit(6, 2, &data).unwrap();
4323
4324        // Predict on the same six samples; rows 0..=2 should share a
4325        // label, rows 3..=5 the other.
4326        let mut labels = vec![0_i32; 6];
4327        km.predict(6, 2, &data, &mut labels).unwrap();
4328        assert_eq!(labels[0], labels[1]);
4329        assert_eq!(labels[1], labels[2]);
4330        assert_eq!(labels[3], labels[4]);
4331        assert_eq!(labels[4], labels[5]);
4332        assert_ne!(labels[0], labels[3]);
4333    }
4334
4335    // ---- reference helpers: naive formulas, independent of AOCL ----
4336
4337    fn near(a: f64, b: f64, tol: f64, what: &str) {
4338        assert!(
4339            (a - b).abs() <= tol * (1.0 + b.abs()),
4340            "{what}: got {a}, want {b}"
4341        );
4342    }
4343
4344    /// Column `j` (axis = Col) or row `i` (axis = Row) of a row-major `r x c` matrix.
4345    fn slices(x: &[f64], r: usize, c: usize, axis: Axis) -> Vec<Vec<f64>> {
4346        match axis {
4347            Axis::Col => (0..c)
4348                .map(|j| (0..r).map(|i| x[i * c + j]).collect())
4349                .collect(),
4350            Axis::Row => (0..r).map(|i| x[i * c..(i + 1) * c].to_vec()).collect(),
4351            _ => unreachable!(),
4352        }
4353    }
4354
4355    const X23: [f64; 6] = [1.0, 2.0, 4.0, 4.0, 8.0, 16.0]; // row-major 2 x 3, all positive
4356
4357    #[test]
4358    fn geometric_mean_matches_exp_mean_log_f64_and_f32() {
4359        for axis in [Axis::Col, Axis::Row] {
4360            let want: Vec<f64> = slices(&X23, 2, 3, axis)
4361                .iter()
4362                .map(|v| (v.iter().map(|x| x.ln()).sum::<f64>() / v.len() as f64).exp())
4363                .collect();
4364            let mut out = vec![0.0_f64; want.len()];
4365            geometric_mean(axis, 2, 3, &X23, &mut out).unwrap();
4366            for (g, w) in out.iter().zip(&want) {
4367                near(*g, *w, 1e-12, "f64 geometric mean");
4368            }
4369            let x32: Vec<f32> = X23.iter().map(|&v| v as f32).collect();
4370            let mut out32 = vec![0.0_f32; want.len()];
4371            geometric_mean(axis, 2, 3, &x32, &mut out32).unwrap();
4372            for (g, w) in out32.iter().zip(&want) {
4373                near(*g as f64, *w, 1e-5, "f32 geometric mean");
4374            }
4375        }
4376        // Closed form: columns of [[1,2,4],[4,8,16]] have geometric means sqrt(4)=2, sqrt(16)=4, sqrt(64)=8.
4377        let mut out = [0.0_f64; 3];
4378        geometric_mean(Axis::Col, 2, 3, &X23, &mut out).unwrap();
4379        for (g, w) in out.iter().zip([2.0, 4.0, 8.0]) {
4380            near(*g, w, 1e-12, "closed-form geometric mean");
4381        }
4382    }
4383
4384    #[test]
4385    fn harmonic_mean_matches_n_over_sum_of_reciprocals_f64_and_f32() {
4386        for axis in [Axis::Col, Axis::Row] {
4387            let want: Vec<f64> = slices(&X23, 2, 3, axis)
4388                .iter()
4389                .map(|v| v.len() as f64 / v.iter().map(|x| 1.0 / x).sum::<f64>())
4390                .collect();
4391            let mut out = vec![0.0_f64; want.len()];
4392            harmonic_mean(axis, 2, 3, &X23, &mut out).unwrap();
4393            for (g, w) in out.iter().zip(&want) {
4394                near(*g, *w, 1e-12, "f64 harmonic mean");
4395            }
4396            let x32: Vec<f32> = X23.iter().map(|&v| v as f32).collect();
4397            let mut out32 = vec![0.0_f32; want.len()];
4398            harmonic_mean(axis, 2, 3, &x32, &mut out32).unwrap();
4399            for (g, w) in out32.iter().zip(&want) {
4400                near(*g as f64, *w, 1e-5, "f32 harmonic mean");
4401            }
4402        }
4403        // Closed form: harmonic mean of {1, 4} = 2 / (1 + 1/4) = 1.6.
4404        let mut out = [0.0_f64; 3];
4405        harmonic_mean(Axis::Col, 2, 3, &X23, &mut out).unwrap();
4406        near(out[0], 1.6, 1e-12, "harmonic mean of column 0");
4407    }
4408
4409    #[test]
4410    fn moment_matches_central_moment_definition_f64_and_f32() {
4411        let x = [
4412            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,
4413        ]; // 4 x 3
4414        for axis in [Axis::Col, Axis::Row] {
4415            let sl = slices(&x, 4, 3, axis);
4416            for k in [2_i64, 3] {
4417                let means: Vec<f64> = sl
4418                    .iter()
4419                    .map(|v| v.iter().sum::<f64>() / v.len() as f64)
4420                    .collect();
4421                let want: Vec<f64> = sl
4422                    .iter()
4423                    .zip(&means)
4424                    .map(|(v, m)| {
4425                        v.iter().map(|x| (x - m).powi(k as i32)).sum::<f64>() / v.len() as f64
4426                    })
4427                    .collect();
4428                let mut mean_out = vec![0.0_f64; sl.len()];
4429                let mut mom = vec![0.0_f64; sl.len()];
4430                moment(axis, 4, 3, &x, k, false, &mut mean_out, &mut mom).unwrap();
4431                for j in 0..sl.len() {
4432                    near(mean_out[j], means[j], 1e-12, "moment: mean output");
4433                    near(mom[j], want[j], 1e-10, "f64 central moment");
4434                }
4435                // Precomputed means supplied: same result.
4436                let mut mom2 = vec![0.0_f64; sl.len()];
4437                let mut means_in = means.clone();
4438                moment(axis, 4, 3, &x, k, true, &mut means_in, &mut mom2).unwrap();
4439                for j in 0..sl.len() {
4440                    near(
4441                        mom2[j],
4442                        want[j],
4443                        1e-10,
4444                        "f64 central moment, precomputed mean",
4445                    );
4446                }
4447                let x32: Vec<f32> = x.iter().map(|&v| v as f32).collect();
4448                let mut m32 = vec![0.0_f32; sl.len()];
4449                let mut mom32 = vec![0.0_f32; sl.len()];
4450                moment(axis, 4, 3, &x32, k, false, &mut m32, &mut mom32).unwrap();
4451                for j in 0..sl.len() {
4452                    near(mom32[j] as f64, want[j], 1e-4, "f32 central moment");
4453                }
4454            }
4455        }
4456    }
4457
4458    #[test]
4459    fn moment_rejects_short_output() {
4460        let mut m = [0.0_f64; 1];
4461        let mut o = [0.0_f64; 1];
4462        assert!(moment(Axis::Col, 2, 3, &X23, 2, false, &mut m, &mut o).is_err());
4463    }
4464
4465    fn dot(a: &[f64], b: &[f64]) -> f64 {
4466        a.iter().zip(b).map(|(x, y)| x * y).sum()
4467    }
4468
4469    #[test]
4470    fn polynomial_and_sigmoid_kernels_match_definitions_f64_and_f32() {
4471        let x = [1.0_f64, 0.5, -1.0, 2.0, 0.0, 1.5]; // 3 x 2 row-major
4472        let y = [0.5_f64, -0.5, 1.0, 1.0]; // 2 x 2
4473        let (gamma, coef0, degree) = (0.5_f64, 1.0_f64, 3_i64);
4474        let rows = |m: &[f64], n: usize| -> Vec<Vec<f64>> {
4475            (0..n).map(|i| m[i * 2..i * 2 + 2].to_vec()).collect()
4476        };
4477        let (xr, yr) = (rows(&x, 3), rows(&y, 2));
4478        // Cross kernel (3 x 2) and self kernel (3 x 3).
4479        for with_y in [true, false] {
4480            let (n, other): (usize, &Vec<Vec<f64>>) = if with_y { (2, &yr) } else { (3, &xr) };
4481            let ys: Option<&[f64]> = if with_y { Some(&y) } else { None };
4482            let mut pd = vec![0.0_f64; 3 * n];
4483            polynomial_kernel(3, n, 2, &x, ys, &mut pd, gamma, degree, coef0).unwrap();
4484            let mut sg = vec![0.0_f64; 3 * n];
4485            sigmoid_kernel(3, n, 2, &x, ys, &mut sg, gamma, coef0).unwrap();
4486            let x32: Vec<f32> = x.iter().map(|&v| v as f32).collect();
4487            let y32: Vec<f32> = y.iter().map(|&v| v as f32).collect();
4488            let ys32: Option<&[f32]> = if with_y { Some(&y32) } else { None };
4489            let mut pd32 = vec![0.0_f32; 3 * n];
4490            polynomial_kernel(
4491                3,
4492                n,
4493                2,
4494                &x32,
4495                ys32,
4496                &mut pd32,
4497                gamma as f32,
4498                degree,
4499                coef0 as f32,
4500            )
4501            .unwrap();
4502            let mut sg32 = vec![0.0_f32; 3 * n];
4503            sigmoid_kernel(3, n, 2, &x32, ys32, &mut sg32, gamma as f32, coef0 as f32).unwrap();
4504            for i in 0..3 {
4505                for j in 0..n {
4506                    let d = dot(&xr[i], &other[j]);
4507                    let wp = (gamma * d + coef0).powi(degree as i32);
4508                    let ws = (gamma * d + coef0).tanh();
4509                    near(pd[i * n + j], wp, 1e-12, "polynomial kernel f64");
4510                    near(sg[i * n + j], ws, 1e-12, "sigmoid kernel f64");
4511                    near(pd32[i * n + j] as f64, wp, 1e-4, "polynomial kernel f32");
4512                    near(sg32[i * n + j] as f64, ws, 1e-5, "sigmoid kernel f32");
4513                }
4514            }
4515        }
4516    }
4517
4518    #[test]
4519    fn datastore_n_cols_and_select_rows() {
4520        use std::io::Write;
4521        let mut path = std::env::temp_dir();
4522        path.push(format!("aocl_da_rows_{}.csv", std::process::id()));
4523        {
4524            let mut f = std::fs::File::create(&path).unwrap();
4525            writeln!(f, "1.0,2.0,3.0").unwrap();
4526            writeln!(f, "4.0,5.0,6.0").unwrap();
4527            writeln!(f, "7.0,8.0,9.0").unwrap();
4528            writeln!(f, "10.0,11.0,12.0").unwrap();
4529        }
4530        let mut store = Datastore::new().unwrap();
4531        assert_eq!(store.n_cols().unwrap(), 0); // empty store (control)
4532        store.load_csv(path.to_str().unwrap()).unwrap();
4533        assert_eq!(store.n_cols().unwrap(), 3);
4534        assert_eq!(store.n_rows().unwrap(), 4);
4535        // Rows 1..=2 (zero-based, inclusive): [[4,5,6],[7,8,9]].
4536        store.select_rows("mid", 1, 2).unwrap();
4537        let mut buf = vec![0.0_f64; 6];
4538        store
4539            .extract_f64("mid", Layout::RowMajor, &mut buf, 3)
4540            .unwrap();
4541        assert_eq!(buf, [4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
4542        // Out-of-range selection is an error.
4543        assert!(store.select_rows("bad", 0, 10).is_err());
4544        let _ = std::fs::remove_file(&path);
4545    }
4546
4547    fn decay_data() -> (Vec<f64>, Vec<f64>) {
4548        let t: Vec<f64> = (0..8).map(|i| i as f64 * 0.5).collect();
4549        let y: Vec<f64> = t.iter().map(|&ti| 2.0 * (-0.3 * ti).exp()).collect();
4550        (t, y)
4551    }
4552
4553    #[test]
4554    fn nlls_with_analytic_jacobian_recovers_parameters() {
4555        let (t, y) = decay_data();
4556        let (t2, y2) = (t.clone(), y.clone());
4557        let model = Nlls::new(2, t.len(), move |x: &[f64], r: &mut [f64]| {
4558            for i in 0..r.len() {
4559                r[i] = x[0] * (-x[1] * t2[i]).exp() - y2[i];
4560            }
4561            0
4562        })
4563        .unwrap();
4564        let t3 = t.clone();
4565        let jac_calls = std::cell::Cell::new(0usize);
4566        let mut model = model
4567            .with_jacobian(|x: &[f64], j: &mut [f64]| {
4568                jac_calls.set(jac_calls.get() + 1);
4569                // Row-major n_res x n_coef: d r_i / d a and d r_i / d b.
4570                for i in 0..t3.len() {
4571                    let e = (-x[1] * t3[i]).exp();
4572                    j[i * 2] = e;
4573                    j[i * 2 + 1] = -x[0] * t3[i] * e;
4574                }
4575                0
4576            })
4577            .unwrap();
4578        let mut coef = vec![1.0_f64, 1.0];
4579        model.fit(&mut coef).unwrap();
4580        near(coef[0], 2.0, 1e-5, "a");
4581        near(coef[1], 0.3, 1e-5, "b");
4582        drop(model);
4583        assert!(
4584            jac_calls.get() > 0,
4585            "the analytic Jacobian was never called"
4586        );
4587    }
4588
4589    #[test]
4590    fn nlls_set_bounds_are_respected_and_wide_bounds_do_not_bind() {
4591        let (t, y) = decay_data();
4592        let make = || {
4593            let (t, y) = (t.clone(), y.clone());
4594            Nlls::new(2, 8, move |x: &[f64], r: &mut [f64]| {
4595                for i in 0..r.len() {
4596                    r[i] = x[0] * (-x[1] * t[i]).exp() - y[i];
4597                }
4598                0
4599            })
4600            .unwrap()
4601        };
4602        // Wide bounds around the truth (a = 2, b = 0.3): the unconstrained answer is recovered.
4603        let mut m = make();
4604        m.set_bounds(Some(&mut [0.0, 0.0]), Some(&mut [10.0, 5.0]))
4605            .unwrap();
4606        let mut c = vec![1.0_f64, 1.0];
4607        m.fit(&mut c).unwrap();
4608        near(c[0], 2.0, 1e-4, "a (wide bounds)");
4609        near(c[1], 0.3, 1e-4, "b (wide bounds)");
4610        // Upper bound a <= 1.5 excludes the true a = 2: the fit must stay feasible, sit on the bound, and leave a
4611        // strictly positive residual (the data are exactly generated by a = 2).
4612        let mut m = make();
4613        m.set_bounds(None, Some(&mut [1.5, 5.0])).unwrap();
4614        let mut c = vec![1.0_f64, 1.0];
4615        m.fit(&mut c).unwrap();
4616        assert!(c[0] <= 1.5 + 1e-9, "a = {} violates a <= 1.5", c[0]);
4617        near(c[0], 1.5, 1e-4, "a sits on its upper bound");
4618        let obj: f64 = (0..8)
4619            .map(|i| (c[0] * (-c[1] * t[i]).exp() - y[i]).powi(2))
4620            .sum();
4621        assert!(obj > 1e-4, "constrained objective {obj} should exceed 0");
4622        // Lower bound b >= 0.5 excludes the true b = 0.3.
4623        let mut m = make();
4624        m.set_bounds(Some(&mut [0.0, 0.5]), None).unwrap();
4625        let mut c = vec![1.0_f64, 1.0];
4626        m.fit(&mut c).unwrap();
4627        assert!(c[1] >= 0.5 - 1e-9, "b = {} violates b >= 0.5", c[1]);
4628        // Too-short bound slices are rejected.
4629        let mut m = make();
4630        assert!(m.set_bounds(Some(&mut [0.0]), None).is_err());
4631    }
4632
4633    #[test]
4634    fn nlls_set_weights_tiny_weight_suppresses_an_outlier() {
4635        let (t, mut y) = decay_data();
4636        y[7] += 5.0; // corrupt the last observation
4637        let make = || {
4638            let (t, y) = (t.clone(), y.clone());
4639            Nlls::new(2, 8, move |x: &[f64], r: &mut [f64]| {
4640                for i in 0..r.len() {
4641                    r[i] = x[0] * (-x[1] * t[i]).exp() - y[i];
4642                }
4643                0
4644            })
4645            .unwrap()
4646        };
4647        // Unweighted: the outlier drags the fit away from the truth (control for the weighted case).
4648        let mut m = make();
4649        let mut c = vec![1.0_f64, 1.0];
4650        m.fit(&mut c).unwrap();
4651        assert!(
4652            (c[0] - 2.0).abs() > 1e-2 || (c[1] - 0.3).abs() > 1e-2,
4653            "outlier had no effect: {c:?}"
4654        );
4655        // Weights w_i = sqrt(W_ii): AOCL rejects zero ("must be sufficiently positive"), so the outlier gets 1e-4, which
4656        // shrinks its pull by 10^4 and recovers the true parameters to ~1e-3.
4657        let mut m = make();
4658        let mut w = vec![1.0_f64; 8];
4659        w[7] = 1e-4;
4660        m.set_weights(&mut w).unwrap();
4661        let mut c = vec![1.0_f64, 1.0];
4662        m.fit(&mut c).unwrap();
4663        near(c[0], 2.0, 3e-3, "a (weighted)");
4664        near(c[1], 0.3, 3e-3, "b (weighted)");
4665        assert!(m.set_weights(&mut [1.0; 3]).is_err());
4666    }
4667
4668    /// Red-first (deterministic by repetition): before the fix a fresh handle returned a string read from uninitialised
4669    /// memory about 1 time in 25 (success status, pointer into uninitialised heap). Now a handle that has seen no failure
4670    /// never reaches the library call, so every one of 2000 fresh handles gives `None`.
4671    #[test]
4672    fn last_error_message_on_a_fresh_handle_is_none_every_time() {
4673        for i in 0..2000 {
4674            let h = Handle::new_double(HandleKind::Linmod).unwrap();
4675            assert_eq!(h.last_error_message(), None, "fresh handle #{i}");
4676        }
4677    }
4678
4679    #[test]
4680    fn last_error_message_names_the_rejected_option() {
4681        let mut h = Handle::new_double(HandleKind::Linmod).unwrap();
4682        assert!(h.set_int_option("no such option", 1).is_err());
4683        let msg = h
4684            .last_error_message()
4685            .expect("an error message after a rejected option");
4686        assert!(!msg.is_empty());
4687        assert!(
4688            msg.contains("no such option"),
4689            "message does not name the option: {msg}"
4690        );
4691    }
4692
4693    // Two separable clusters in 2-D, column-major (feature 0 then feature 1): class 0 near (0,0), class 1 near (10,10).
4694    const CL_X: [f64; 12] = [
4695        0.0, 0.1, 0.2, 10.0, 10.1, 10.2, 0.1, 0.0, 0.1, 10.1, 10.0, 10.1,
4696    ];
4697    const CL_Y: [i32; 6] = [0, 0, 0, 1, 1, 1];
4698    const CL_TEST: [f64; 4] = [0.05, 9.95, 0.05, 10.05]; // (0.05,0.05) and (9.95,10.05)
4699
4700    #[test]
4701    fn knn_classes_lists_distinct_labels_whatever_the_buffer_size() {
4702        let mut knn = KNearestNeighbours::new().unwrap();
4703        knn.fit(6, 2, &CL_X, &[7, 7, 7, 3, 3, 3]).unwrap();
4704        // Ascending distinct labels; the return value is the number of classes, not the buffer length.
4705        let mut big = [0_i32; 5];
4706        assert_eq!(knn.classes(&mut big).unwrap(), 2);
4707        assert_eq!(&big[..2], &[3, 7]);
4708        let mut exact = [0_i32; 2];
4709        assert_eq!(knn.classes(&mut exact).unwrap(), 2);
4710        assert_eq!(exact, [3, 7]);
4711    }
4712
4713    #[test]
4714    fn knn_kneighbors_match_brute_force_ranking() {
4715        let mut knn = KNearestNeighbours::new().unwrap();
4716        knn.fit(6, 2, &CL_X, &CL_Y).unwrap();
4717        // Queries (0.04, 0.02) and (10.15, 10.0): no distance ties among the training points.
4718        let q = [0.04, 10.15, 0.02, 10.0];
4719        let k = 3;
4720        let mut ind = vec![0_i32; 2 * k];
4721        let mut dist = vec![0.0_f64; 2 * k];
4722        knn.kneighbors(2, 2, &q, &mut ind, &mut dist, k, true)
4723            .unwrap();
4724        for qi in 0..2 {
4725            let mut ranked: Vec<(f64, i32)> = (0..6)
4726                .map(|i| {
4727                    (
4728                        ((CL_X[i] - q[qi]).powi(2) + (CL_X[6 + i] - q[2 + qi]).powi(2)).sqrt(),
4729                        i as i32,
4730                    )
4731                })
4732                .collect();
4733            ranked.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap());
4734            for j in 0..k {
4735                // Column-major (n_queries x k): element (query, rank) at rank * n_queries + query.
4736                assert_eq!(ind[j * 2 + qi], ranked[j].1, "query {qi} rank {j}");
4737                near(dist[j * 2 + qi], ranked[j].0, 1e-9, "neighbour distance");
4738            }
4739        }
4740        // Without distances the indices are the same.
4741        let mut ind2 = vec![0_i32; 2 * k];
4742        let mut dist2 = vec![0.0_f64; 2 * k];
4743        knn.kneighbors(2, 2, &q, &mut ind2, &mut dist2, k, false)
4744            .unwrap();
4745        assert_eq!(ind, ind2);
4746    }
4747
4748    #[test]
4749    fn knn_predict_proba_counts_neighbour_classes() {
4750        // Default k = 5 with 3 training points per class: a query always has all 3 of its own cluster plus the 2
4751        // 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
4752        // cluster 1. The 3 x 2 result is column-major (ldp = n_queries): element (query, class) at class * 3 + query.
4753        let mut knn = KNearestNeighbours::new().unwrap();
4754        knn.fit(6, 2, &CL_X, &CL_Y).unwrap();
4755        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)
4756        let mut proba = vec![0.0_f64; 6];
4757        knn.predict_proba(3, 2, &q, &mut proba).unwrap();
4758        for (g, w) in proba.iter().zip([0.6, 0.6, 0.4, 0.4, 0.4, 0.6]) {
4759            near(*g, w, 1e-9, "knn predict_proba");
4760        }
4761    }
4762
4763    #[test]
4764    fn dbscan_core_sample_indices_exclude_noise() {
4765        // Five points in a tight cluster plus one far outlier: with min samples = 3 and eps = 1 the cluster points
4766        // (indices 0..=4) are core samples, the outlier (index 5) is noise (label -1) and not core.
4767        let data: Vec<f64> = vec![
4768            0.0, 0.1, 0.2, 0.0, 0.1, 50.0, // feature 0
4769            0.0, 0.1, 0.0, 0.2, 0.1, 50.0, // feature 1
4770        ];
4771        let mut db = Dbscan::new().unwrap();
4772        let cs = std::ffi::CString::new("eps").unwrap();
4773        let st = unsafe { sys::da_options_set_real_d(db.handle_mut().as_raw(), cs.as_ptr(), 1.0) };
4774        assert_eq!(st, sys::da_status__da_status_success);
4775        db.handle_mut().set_int_option("min samples", 3).unwrap();
4776        db.fit(6, 2, &data).unwrap();
4777        let mut core = db.core_sample_indices().unwrap();
4778        core.sort();
4779        assert_eq!(core, vec![0, 1, 2, 3, 4]);
4780        assert_eq!(core.len(), db.n_core_samples().unwrap());
4781        let labels = db.labels().unwrap();
4782        assert_eq!(labels[5], -1);
4783        assert!(labels[..5].iter().all(|&l| l == labels[0] && l >= 0));
4784    }
4785
4786    // Four queries (column-major, feature 0 then feature 1): classes 0, 1, 0, 1.
4787    const Q4: [f64; 8] = [0.05, 9.95, 0.2, 10.2, 0.05, 10.05, 0.0, 10.1];
4788
4789    /// Probability outputs are laid out in the handle's storage order (column-major, `ldy >= n_samples`): element
4790    /// (sample `i`, class `c`) is at `c * ldy + i`. (The wrapper's docs say row-major / `ldy >= n_class`: FINDING.)
4791    #[test]
4792    fn tree_and_forest_predict_proba_and_log_proba_on_separable_data() {
4793        let mut tree = DecisionTree::new().unwrap();
4794        tree.fit(6, 2, 2, &CL_X, &CL_Y).unwrap();
4795        let mut forest = DecisionForest::new().unwrap();
4796        forest.fit(6, 2, 2, &CL_X, &CL_Y).unwrap();
4797        let truth = [0usize, 1, 0, 1];
4798        let at = |v: &[f64], i: usize, c: usize| v[c * 4 + i];
4799
4800        let mut tp = vec![0.0_f64; 8];
4801        tree.predict_proba(4, 2, &Q4, &mut tp, 2, 4).unwrap();
4802        for i in 0..4 {
4803            for c in 0..2 {
4804                near(
4805                    at(&tp, i, c),
4806                    if c == truth[i] { 1.0 } else { 0.0 },
4807                    1e-12,
4808                    "tree proba (pure leaves)",
4809                );
4810            }
4811        }
4812        let mut tl = vec![0.0_f64; 8];
4813        tree.predict_log_proba(4, 2, &Q4, &mut tl, 2, 4).unwrap();
4814        for i in 0..4 {
4815            near(
4816                at(&tl, i, truth[i]),
4817                0.0,
4818                1e-12,
4819                "tree log P(true class) = ln 1",
4820            );
4821            assert!(
4822                at(&tl, i, 1 - truth[i]) < -10.0,
4823                "ln 0 must be very negative: {tl:?}"
4824            );
4825        }
4826
4827        let mut fp = vec![0.0_f64; 8];
4828        forest.predict_proba(4, 2, &Q4, &mut fp, 2, 4).unwrap();
4829        for i in 0..4 {
4830            near(
4831                at(&fp, i, 0) + at(&fp, i, 1),
4832                1.0,
4833                1e-9,
4834                "forest probabilities sum to 1",
4835            );
4836            assert!(at(&fp, i, truth[i]) > 0.8, "forest proba {fp:?}");
4837        }
4838        let mut fl = vec![0.0_f64; 8];
4839        forest.predict_log_proba(4, 2, &Q4, &mut fl, 2, 4).unwrap();
4840        // exp(log P) reproduces P wherever P > 0 (the invariant tying the two outputs together).
4841        for (l, p) in fl.iter().zip(&fp) {
4842            if *p > 1e-12 {
4843                near(l.exp(), *p, 1e-9, "forest exp(log_proba) == proba");
4844            }
4845        }
4846    }
4847
4848    #[test]
4849    fn linmod_logistic_separates_two_classes() {
4850        // 1-D, linearly separable at 0: class 0 for x < 0, class 1 for x > 0.
4851        let x = [-2.0_f64, -1.0, -0.5, 0.5, 1.0, 2.0];
4852        let y = [0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4853        let mut m = Linmod::new_logistic().unwrap();
4854        assert_eq!(m.kind(), LinmodKind::Logistic);
4855        m.fit(6, 1, &x, &y).unwrap();
4856        let coefs = m.coefficients().unwrap();
4857        assert!(
4858            coefs[0] > 0.0,
4859            "slope of a positively separated problem must be > 0: {coefs:?}"
4860        );
4861        let mut pred = vec![0.0_f64; 6];
4862        m.predict(6, 1, &x, &mut pred).unwrap();
4863        assert_eq!(pred, y);
4864        // Unseen points on either side of the boundary.
4865        let mut p2 = [0.0_f64; 2];
4866        m.predict(2, 1, &[-3.0, 3.0], &mut p2).unwrap();
4867        assert_eq!(p2, [0.0, 1.0]);
4868    }
4869
4870    fn set_real(svm: &mut Svm, name: &str, v: f64) {
4871        let cs = std::ffi::CString::new(name).unwrap();
4872        let st = unsafe { sys::da_options_set_real_d(svm.handle_mut().as_raw(), cs.as_ptr(), v) };
4873        assert_eq!(st, sys::da_status__da_status_success, "option {name}");
4874    }
4875
4876    #[test]
4877    fn svm_nu_svc_separates_two_classes() {
4878        let y = [0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4879        let mut svm = Svm::new_nu_svc().unwrap();
4880        assert_eq!(svm.kind(), SvmKind::NuSvc);
4881        svm.fit(6, 2, &CL_X, &y).unwrap();
4882        let mut p = [0.0_f64; 2];
4883        svm.predict(2, 2, &CL_TEST, &mut p).unwrap();
4884        assert_eq!(p, [0.0, 1.0]);
4885        near(
4886            svm.score(6, 2, &CL_X, &y).unwrap(),
4887            1.0,
4888            1e-12,
4889            "nu-svc training accuracy",
4890        );
4891    }
4892
4893    #[test]
4894    fn svm_decision_function_sign_separates_classes() {
4895        let y = [0.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0];
4896        let mut svm = Svm::new_svc().unwrap();
4897        svm.fit(6, 2, &CL_X, &y).unwrap();
4898        for shape in [DecisionShape::Ovo, DecisionShape::Ovr] {
4899            let mut dv = vec![0.0_f64; 2];
4900            svm.decision_function(2, 2, &CL_TEST, shape, &mut dv, 2)
4901                .unwrap();
4902            // Binary problem (scikit-learn convention): positive value <=> the second class.
4903            assert!(dv[0] < 0.0 && dv[1] > 0.0, "{shape:?}: {dv:?}");
4904        }
4905        // On the training set every class-1 sample scores above every class-0 sample.
4906        let mut dv = vec![0.0_f64; 6];
4907        svm.decision_function(6, 2, &CL_X, DecisionShape::Ovo, &mut dv, 6)
4908            .unwrap();
4909        let max0 = dv[..3].iter().cloned().fold(f64::MIN, f64::max);
4910        let min1 = dv[3..].iter().cloned().fold(f64::MAX, f64::min);
4911        assert!(max0 < min1, "{dv:?}");
4912    }
4913
4914    /// y = 2x + 1 sampled at x = 0..=9: a linear-kernel SVR with a large C must reproduce it within its epsilon tube.
4915    fn regression_data() -> (Vec<f64>, Vec<f64>) {
4916        let x: Vec<f64> = (0..10).map(|i| i as f64).collect();
4917        let y: Vec<f64> = x.iter().map(|&v| 2.0 * v + 1.0).collect();
4918        (x, y)
4919    }
4920
4921    #[test]
4922    fn svm_svr_fits_a_line() {
4923        let (x, y) = regression_data();
4924        let mut svm = Svm::new_svr().unwrap();
4925        assert_eq!(svm.kind(), SvmKind::Svr);
4926        svm.handle_mut()
4927            .set_string_option("kernel", "linear")
4928            .unwrap();
4929        set_real(&mut svm, "C", 1000.0);
4930        set_real(&mut svm, "epsilon", 0.1);
4931        svm.fit(10, 1, &x, &y).unwrap();
4932        let mut p = vec![0.0_f64; 10];
4933        svm.predict(10, 1, &x, &mut p).unwrap();
4934        for (g, w) in p.iter().zip(&y) {
4935            // Epsilon-insensitive loss: training points lie within epsilon (+ solver slack) of the truth.
4936            assert!((g - w).abs() < 0.2, "svr pred {g} vs {w}");
4937        }
4938        assert!(svm.score(10, 1, &x, &y).unwrap() > 0.99);
4939    }
4940
4941    #[test]
4942    fn svm_nu_svr_fits_a_line() {
4943        let (x, y) = regression_data();
4944        let mut svm = Svm::new_nu_svr().unwrap();
4945        assert_eq!(svm.kind(), SvmKind::NuSvr);
4946        svm.handle_mut()
4947            .set_string_option("kernel", "linear")
4948            .unwrap();
4949        set_real(&mut svm, "C", 1000.0);
4950        svm.fit(10, 1, &x, &y).unwrap();
4951        let mut p = vec![0.0_f64; 10];
4952        svm.predict(10, 1, &x, &mut p).unwrap();
4953        for (g, w) in p.iter().zip(&y) {
4954            assert!((g - w).abs() < 0.5, "nu-svr pred {g} vs {w}");
4955        }
4956        assert!(svm.score(10, 1, &x, &y).unwrap() > 0.99);
4957        // Extrapolation follows the line (slope 2): f(12) ~ 25.
4958        let mut q = [0.0_f64; 1];
4959        svm.predict(1, 1, &[12.0], &mut q).unwrap();
4960        assert!((q[0] - 25.0).abs() < 1.0, "f(12) = {}", q[0]);
4961    }
4962}