Skip to main content

aocl_data_analytics/
lib.rs

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