Skip to main content

aocl_data_analytics/
lib.rs

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