Skip to main content

aocl_data_analytics/
lib.rs

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