Skip to main content

aocl_data_analytics/
lib.rs

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