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