1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Summary statistics — `vsl?SS*` task family.
//!
//! Computes per-variable statistics (mean, variance, min, max, sum)
//! over a `(p × n)` data matrix where `p` is the number of variables
//! and `n` is the number of observations.
//!
//! Data is row-major in the natural sense: variable `i`'s
//! observations live at `data[i * n + 0 .. i * n + n]`.
//!
//! ```no_run
//! use onemkl::rng::summary_stats::SummaryStats;
//!
//! // 1 variable, 5 observations.
//! let data = [1.0_f64, 2.0, 3.0, 4.0, 5.0];
//! let mut ss = SummaryStats::<f64>::new(&data, 1, 5).unwrap();
//! let mean = ss.mean().unwrap();
//! assert!((mean[0] - 3.0).abs() < 1e-12);
//! ```
use core::ffi::c_int;
use core::marker::PhantomData;
use core::ptr;
use onemkl_sys::{self as sys, VSLSSTaskPtr};
use crate::error::{Error, Result};
/// Real scalar types supported by the summary-statistics task family.
#[allow(missing_docs)]
pub trait SsScalar: Copy + Default + 'static {
/// Raw `ss_new_task` call.
///
/// # Safety
///
/// `task` must be valid for a write of one `VSLSSTaskPtr`. `p`, `n` and `xstorage` must each point to one readable `c_int` (dimension `p >= 1`, observation count `n >= 1`, and a `VSL_SS_MATRIX_STORAGE_*` constant); they are read during the call.
/// `x` must point to the `p x n` observation matrix, `p * n` elements, stored per `*xstorage`. `w` may be null (equal weights) or point to `n` weights. `indices` may be null or point to `p` entries of 0/1 selecting which variables are used.
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// On a non-zero return `*task` must not be used. A non-zero return is the VSL status. The MKL library must be linked and usable.
/// **Verified** by guard-page probe (smallest buffer for which the call did not fault: `x`: p * n and `w`: n elements, row storage; oneMKL 2026.2, Linux x86_64). Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_new_task(
task: *mut VSLSSTaskPtr,
p: *const c_int,
n: *const c_int,
xstorage: *const c_int,
x: *const Self,
w: *const Self,
indices: *const c_int,
) -> c_int;
/// Raw `ss_edit_task` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `parameter` must be a `VSL_SS_ED_*` constant that expects a `Self`-typed address (or the matching integer type, which this method does not provide); `address` must point to storage of the extent MKL documents for that parameter (for example `p` elements for a per-variable vector, `p * p` for a covariance matrix).
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_edit_task(task: VSLSSTaskPtr, parameter: c_int, address: *const Self) -> c_int;
/// Raw `ss_edit_moments` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `mean`, `r2m`, `r3m`, `r4m`, `c2m`, `c3m` and `c4m` are output vectors of `p` elements each (the task dimension); each pointer must be non-null and valid for writes of `p` elements when the corresponding estimate is requested in `ss_compute`, and the buffers must not overlap each other or the task data.
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// **Verified** by guard-page probe (smallest buffer for which the call did not fault: `mean` and `r2m` (raw 2nd moment): p elements each; note 2C_MOM needs the 2R_MOM output registered, status -4007 otherwise; oneMKL 2026.2, Linux x86_64). Extents not listed as verified in this block are unverified (from MKL documentation).
#[allow(
clippy::too_many_arguments,
reason = "mirrors the oneMKL C signature vsl?SSEditMoments argument for argument"
)]
unsafe fn ss_edit_moments(
task: VSLSSTaskPtr,
mean: *mut Self,
r2m: *mut Self,
r3m: *mut Self,
r4m: *mut Self,
c2m: *mut Self,
c3m: *mut Self,
c4m: *mut Self,
) -> c_int;
/// Raw `ss_compute` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// All pointers previously registered with the task via `ss_new_task` and the `ss_edit_*` calls must still be valid per their own contracts. `estimates` must be a bitwise OR of `VSL_SS_*` estimate flags for which the corresponding output buffers were registered; otherwise MKL writes through unset pointers. `method` must be a valid `VSL_SS_METHOD_*`.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_compute(task: VSLSSTaskPtr, estimates: u64, method: c_int) -> c_int;
/// Raw `ss_edit_quantiles` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `quant_order_n` points to one `c_int` (number of quantile orders `m`); `quant_orders` points to `m` values in `[0, 1]`; `quants_out` must be valid for writes of `p * m` elements; `order_stats_out` and `order_stats_storage` may be null together, otherwise `order_stats_out` must be valid for writes of `p * n` elements stored per `*order_stats_storage`.
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// **Verified** by guard-page probe (smallest buffer for which the call did not fault: `quants_out`: p * q elements; oneMKL 2026.2, Linux x86_64). Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_edit_quantiles(
task: VSLSSTaskPtr,
quant_order_n: *const c_int,
quant_orders: *const Self,
quants_out: *mut Self,
order_stats_out: *mut Self,
order_stats_storage: *const c_int,
) -> c_int;
/// Raw `ss_edit_stream_quantiles` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `quant_order_n` points to one `c_int` (`m`); `quant_orders` points to `m` values in `[0, 1]`; `quants_out` must be valid for writes of `p * m` elements; `params_n` points to one `c_int` (the number of parameters, at least 1) and `params` to that many values (the accuracy parameter).
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// **Verified** by guard-page probe (`tools/size-probes/ss2.c`, smallest buffer for which the call did not fault, p = 3, n = 40, row storage; oneMKL 2026.2, Linux x86_64): `quants_out`: p * m elements (m = 3 orders; ZW method, accuracy 0.01, computed over one batch of n observations, not a multi-block stream).
/// Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_edit_stream_quantiles(
task: VSLSSTaskPtr,
quant_order_n: *const c_int,
quant_orders: *const Self,
quants_out: *mut Self,
params_n: *const c_int,
params: *const Self,
) -> c_int;
/// Raw `ss_edit_robust_covariance` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `cov_storage` points to one `c_int` giving the storage of `cov_out` (a `VSL_SS_MATRIX_STORAGE_*`); `n_params` points to one `c_int` and `params` to that many parameters; `mean_out` must be valid for writes of `p` elements and `cov_out` of `p * p` elements (or the packed size for packed storage).
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// **Verified** by guard-page probe (`tools/size-probes/ss2.c`, smallest buffer for which the call did not fault, p = 3, n = 40, row storage; oneMKL 2026.2, Linux x86_64): `mean_out`: p and `cov_out`: p * p elements (full storage, TBS method with 4 parameters).
/// Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_edit_robust_covariance(
task: VSLSSTaskPtr,
cov_storage: *const c_int,
n_params: *const c_int,
params: *const Self,
mean_out: *mut Self,
cov_out: *mut Self,
) -> c_int;
/// Raw `ss_edit_outliers_detection` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `n_params` points to one `c_int` and `params` to that many parameters (3 as MKL documents); `weights_out` must be valid for writes of `n` elements (one weight per observation).
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// **Verified** by guard-page probe (`tools/size-probes/ss2.c`, smallest buffer for which the call did not fault, p = 3, n = 40, row storage; oneMKL 2026.2, Linux x86_64): `weights_out`: n elements (BACON method with 3 parameters).
/// Extents not listed as verified in this block are unverified (from MKL documentation).
unsafe fn ss_edit_outliers_detection(
task: VSLSSTaskPtr,
n_params: *const c_int,
params: *const Self,
weights_out: *mut Self,
) -> c_int;
/// Raw `ss_edit_missing_values` call.
///
/// # Safety
///
/// `task` must be a live `VSLSSTaskPtr` from `ss_new_task` that has not been deleted, and must not be used from another thread during the call.
/// `n_params`/`params`, `init_estimates_n`/`init_estimates`, `prior_n`/`prior` and `simul_vals_n`/`estimates_n` are (count, data) pairs: each count points to one `c_int` and the paired data to that many `Self` values (null where MKL allows a default). `simul_vals_out` must be valid for writes of `simul_vals * p` elements and `estimates_out` of the estimates the task defines (the mean `p` and covariance `p * p` as requested).
/// **Pointer retention:** the task stores the pointers it is given (it does not copy the data). Each buffer must stay allocated, at a stable address, and not be mutated through Rust references (outputs: not accessed at all) from this call until the task has been deleted or the pointer replaced, including across every `ss_compute` call.
/// A non-zero return is the VSL status. The MKL library must be linked and usable.
/// Extents not listed as verified in this block are unverified (from MKL documentation).
#[allow(
clippy::too_many_arguments,
reason = "mirrors the oneMKL C signature vsl?SSEditMissingValues argument for argument"
)]
unsafe fn ss_edit_missing_values(
task: VSLSSTaskPtr,
n_params: *const c_int,
params: *const Self,
init_estimates_n: *const c_int,
init_estimates: *const Self,
prior_n: *const c_int,
prior: *const Self,
simul_vals_n: *const c_int,
simul_vals_out: *mut Self,
estimates_n: *const c_int,
estimates_out: *mut Self,
) -> c_int;
}
macro_rules! impl_ss_scalar {
($ty:ty,
new=$new:ident, edit=$edit:ident,
moments=$moments:ident, compute=$compute:ident,
quantiles=$quantiles:ident, stream_quantiles=$stream_quantiles:ident,
robust_cov=$robust_cov:ident, outliers=$outliers:ident,
missing=$missing:ident,
) => {
impl SsScalar for $ty {
unsafe fn ss_new_task(
task: *mut VSLSSTaskPtr,
p: *const c_int,
n: *const c_int,
xstorage: *const c_int,
x: *const Self,
w: *const Self,
indices: *const c_int,
) -> c_int {
unsafe { sys::$new(task, p, n, xstorage, x, w, indices) }
}
unsafe fn ss_edit_task(
task: VSLSSTaskPtr,
parameter: c_int,
address: *const Self,
) -> c_int {
unsafe { sys::$edit(task, parameter, address) }
}
unsafe fn ss_edit_moments(
task: VSLSSTaskPtr,
mean: *mut Self,
r2m: *mut Self,
r3m: *mut Self,
r4m: *mut Self,
c2m: *mut Self,
c3m: *mut Self,
c4m: *mut Self,
) -> c_int {
unsafe { sys::$moments(task, mean, r2m, r3m, r4m, c2m, c3m, c4m) }
}
unsafe fn ss_compute(task: VSLSSTaskPtr, estimates: u64, method: c_int) -> c_int {
unsafe { sys::$compute(task, estimates, method) }
}
unsafe fn ss_edit_quantiles(
task: VSLSSTaskPtr,
quant_order_n: *const c_int,
quant_orders: *const Self,
quants_out: *mut Self,
order_stats_out: *mut Self,
order_stats_storage: *const c_int,
) -> c_int {
unsafe {
sys::$quantiles(
task,
quant_order_n,
quant_orders,
quants_out,
order_stats_out,
order_stats_storage,
)
}
}
unsafe fn ss_edit_stream_quantiles(
task: VSLSSTaskPtr,
quant_order_n: *const c_int,
quant_orders: *const Self,
quants_out: *mut Self,
params_n: *const c_int,
params: *const Self,
) -> c_int {
unsafe {
sys::$stream_quantiles(
task,
quant_order_n,
quant_orders,
quants_out,
params_n,
params,
)
}
}
unsafe fn ss_edit_robust_covariance(
task: VSLSSTaskPtr,
cov_storage: *const c_int,
n_params: *const c_int,
params: *const Self,
mean_out: *mut Self,
cov_out: *mut Self,
) -> c_int {
unsafe { sys::$robust_cov(task, cov_storage, n_params, params, mean_out, cov_out) }
}
unsafe fn ss_edit_outliers_detection(
task: VSLSSTaskPtr,
n_params: *const c_int,
params: *const Self,
weights_out: *mut Self,
) -> c_int {
unsafe { sys::$outliers(task, n_params, params, weights_out) }
}
unsafe fn ss_edit_missing_values(
task: VSLSSTaskPtr,
n_params: *const c_int,
params: *const Self,
init_estimates_n: *const c_int,
init_estimates: *const Self,
prior_n: *const c_int,
prior: *const Self,
simul_vals_n: *const c_int,
simul_vals_out: *mut Self,
estimates_n: *const c_int,
estimates_out: *mut Self,
) -> c_int {
unsafe {
sys::$missing(
task,
n_params,
params,
init_estimates_n,
init_estimates,
prior_n,
prior,
simul_vals_n,
simul_vals_out,
estimates_n,
estimates_out,
)
}
}
}
};
}
impl_ss_scalar!(
f32,
new = vslsSSNewTask,
edit = vslsSSEditTask,
moments = vslsSSEditMoments,
compute = vslsSSCompute,
quantiles = vslsSSEditQuantiles,
stream_quantiles = vslsSSEditStreamQuantiles,
robust_cov = vslsSSEditRobustCovariance,
outliers = vslsSSEditOutliersDetection,
missing = vslsSSEditMissingValues,
);
impl_ss_scalar!(
f64,
new = vsldSSNewTask,
edit = vsldSSEditTask,
moments = vsldSSEditMoments,
compute = vsldSSCompute,
quantiles = vsldSSEditQuantiles,
stream_quantiles = vsldSSEditStreamQuantiles,
robust_cov = vsldSSEditRobustCovariance,
outliers = vsldSSEditOutliersDetection,
missing = vsldSSEditMissingValues,
);
/// Owned summary-statistics task. Each compute method registers output
/// buffers internally and runs `vsl?SSCompute`.
pub struct SummaryStats<'data, T: SsScalar> {
task: VSLSSTaskPtr,
p: usize,
_n: usize,
// MKL stores raw pointers to these inside the task, so they must
// outlive every Edit/Compute call. Boxed so the addresses are
// stable across moves of `Self`.
_p_holder: Box<c_int>,
_n_holder: Box<c_int>,
_xstorage_holder: Box<c_int>,
_data: &'data [T],
_marker: PhantomData<T>,
}
unsafe impl<T: SsScalar + Send> Send for SummaryStats<'_, T> {}
impl<'data, T: SsScalar> SummaryStats<'data, T> {
/// Build a task over `num_variables × num_observations` data laid
/// out so variable `i` occupies `data[i * num_observations ..]`.
pub fn new(data: &'data [T], num_variables: usize, num_observations: usize) -> Result<Self> {
if data.len() < num_variables * num_observations {
return Err(Error::InvalidArgument(
"data buffer is smaller than num_variables * num_observations",
));
}
let p_box: Box<c_int> = Box::new(
num_variables
.try_into()
.map_err(|_| Error::DimensionOverflow)?,
);
let n_box: Box<c_int> = Box::new(
num_observations
.try_into()
.map_err(|_| Error::DimensionOverflow)?,
);
let xstorage_box: Box<c_int> = Box::new(sys::VSL_SS_MATRIX_STORAGE_ROWS as c_int);
let mut task: VSLSSTaskPtr = ptr::null_mut();
let status = unsafe {
T::ss_new_task(
&mut task,
&*p_box,
&*n_box,
&*xstorage_box,
data.as_ptr(),
ptr::null(),
ptr::null(),
)
};
check_vsl(status)?;
Ok(Self {
task,
p: num_variables,
_n: num_observations,
_p_holder: p_box,
_n_holder: n_box,
_xstorage_holder: xstorage_box,
_data: data,
_marker: PhantomData,
})
}
/// Per-variable mean. Length is `num_variables`.
pub fn mean(&mut self) -> Result<Vec<T>> {
let mut mean = vec![T::default(); self.p];
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_MEAN as c_int, mean.as_mut_ptr()) };
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_MEAN as u64,
sys::VSL_SS_METHOD_FAST as c_int,
)
};
check_vsl(status)?;
Ok(mean)
}
/// Per-variable variance (2nd central moment). Length is
/// `num_variables`. Computing variance also requires mean and the
/// raw 2nd moment to be registered; the wrapper allocates
/// temporary buffers for both and discards them.
pub fn variance(&mut self) -> Result<Vec<T>> {
let mut mean = vec![T::default(); self.p];
let mut r2m = vec![T::default(); self.p];
let mut c2m = vec![T::default(); self.p];
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_MEAN as c_int, mean.as_mut_ptr()) };
check_vsl(status)?;
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_2R_MOM as c_int, r2m.as_mut_ptr()) };
check_vsl(status)?;
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_2C_MOM as c_int, c2m.as_mut_ptr()) };
check_vsl(status)?;
let estimates = (sys::VSL_SS_MEAN | sys::VSL_SS_2R_MOM | sys::VSL_SS_2C_MOM) as u64;
let status =
unsafe { T::ss_compute(self.task, estimates, sys::VSL_SS_METHOD_FAST as c_int) };
check_vsl(status)?;
Ok(c2m)
}
/// Per-variable minimum. Length is `num_variables`. The MKL min
/// estimator must be seeded from an observation, so the wrapper
/// initializes the result with the first observation of each
/// variable before computing.
pub fn min(&mut self) -> Result<Vec<T>> {
let mut min = self.seed_from_first_observation();
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_MIN as c_int, min.as_mut_ptr()) };
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_MIN as u64,
sys::VSL_SS_METHOD_FAST as c_int,
)
};
check_vsl(status)?;
Ok(min)
}
/// Per-variable maximum. See [`min`](Self::min) for the seeding
/// note.
pub fn max(&mut self) -> Result<Vec<T>> {
let mut max = self.seed_from_first_observation();
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_MAX as c_int, max.as_mut_ptr()) };
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_MAX as u64,
sys::VSL_SS_METHOD_FAST as c_int,
)
};
check_vsl(status)?;
Ok(max)
}
/// Build a length-`p` vector seeded from the first observation of
/// each variable. Used to initialize min/max estimators.
fn seed_from_first_observation(&self) -> Vec<T> {
let n = self._n;
(0..self.p).map(|i| self._data[i * n]).collect()
}
/// Per-variable sum. Length is `num_variables`.
pub fn sum(&mut self) -> Result<Vec<T>> {
let mut sum = vec![T::default(); self.p];
let status =
unsafe { T::ss_edit_task(self.task, sys::VSL_SS_ED_SUM as c_int, sum.as_mut_ptr()) };
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_SUM as u64,
sys::VSL_SS_METHOD_FAST as c_int,
)
};
check_vsl(status)?;
Ok(sum)
}
/// Per-variable quantiles at the requested `orders` (e.g.
/// `[0.25, 0.5, 0.75]` for Q1 / median / Q3). Returns a flat
/// vector laid out as `num_variables × orders.len()`, where
/// `result[i * orders.len() + j]` is variable `i`'s `orders[j]`
/// quantile.
///
/// All order values must lie in `(0, 1)`.
pub fn quantiles(&mut self, orders: &[T]) -> Result<Vec<T>>
where
T: PartialOrd,
{
if orders.is_empty() {
return Err(Error::InvalidArgument("orders must be non-empty"));
}
let order_n: c_int = orders
.len()
.try_into()
.map_err(|_| Error::DimensionOverflow)?;
let mut out = vec![T::default(); self.p * orders.len()];
let status = unsafe {
T::ss_edit_quantiles(
self.task,
&order_n,
orders.as_ptr(),
out.as_mut_ptr(),
ptr::null_mut(),
ptr::null(),
)
};
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_QUANTS as u64,
sys::VSL_SS_METHOD_FAST as c_int,
)
};
check_vsl(status)?;
Ok(out)
}
/// Streaming-quantile estimator (Zhang-Wang). Suitable for
/// online data where you can't hold the full sample but want an
/// approximate quantile. `params` controls the estimator
/// (typically `[buffer_size_per_quantile]`). Returns the same
/// `num_variables × orders.len()` layout as [`Self::quantiles`].
pub fn stream_quantiles(&mut self, orders: &[T], params: &[T]) -> Result<Vec<T>> {
if orders.is_empty() {
return Err(Error::InvalidArgument("orders must be non-empty"));
}
let order_n: c_int = orders
.len()
.try_into()
.map_err(|_| Error::DimensionOverflow)?;
let params_n: c_int = params
.len()
.try_into()
.map_err(|_| Error::DimensionOverflow)?;
let mut out = vec![T::default(); self.p * orders.len()];
let status = unsafe {
T::ss_edit_stream_quantiles(
self.task,
&order_n,
orders.as_ptr(),
out.as_mut_ptr(),
¶ms_n,
params.as_ptr(),
)
};
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_STREAM_QUANTS as u64,
sys::VSL_SS_METHOD_FAST as c_int,
)
};
check_vsl(status)?;
Ok(out)
}
/// Robust covariance + mean via Tukey's bi-weight S-estimator
/// (`VSL_SS_METHOD_TBS` in MKL).
///
/// Returns `(mean, cov)` where `cov` is the `p × p` covariance
/// stored in column-major (full) layout. `params` is the TBS
/// configuration — pass an empty slice to accept MKL's defaults,
/// or supply `[breakdown_point]` (typical value `0.5`) to control
/// the maximum fraction of outliers the estimator tolerates.
///
/// Note: MKL exposes BACON only for *outlier weights*
/// (see [`Self::outliers_bacon`]); for a full robust covariance
/// estimate the supported algorithm is TBS.
pub fn robust_covariance_tbs(&mut self, params: &[T]) -> Result<(Vec<T>, Vec<T>)> {
let cov_storage: c_int = sys::VSL_SS_MATRIX_STORAGE_FULL as c_int;
let n_params: c_int = params
.len()
.try_into()
.map_err(|_| Error::DimensionOverflow)?;
let mut mean = vec![T::default(); self.p];
let mut cov = vec![T::default(); self.p * self.p];
let status = unsafe {
T::ss_edit_robust_covariance(
self.task,
&cov_storage,
&n_params,
if params.is_empty() {
ptr::null()
} else {
params.as_ptr()
},
mean.as_mut_ptr(),
cov.as_mut_ptr(),
)
};
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_ROBUST_COV as u64,
sys::VSL_SS_METHOD_TBS as c_int,
)
};
check_vsl(status)?;
Ok((mean, cov))
}
/// Per-observation outlier weights via BACON (Blocked Adaptive
/// Computationally-efficient Outlier Nominators). Returns a
/// vector of length `num_observations`: `1.0` for inliers,
/// `0.0` for flagged outliers.
///
/// `params` is BACON's 3-element configuration:
///
/// - `params[0]` = initialization method
/// (`VSL_SS_METHOD_BACON_MEDIAN_INIT` or
/// `VSL_SS_METHOD_BACON_MAHALANOBIS_INIT` from `onemkl-sys`),
/// - `params[1]` = significance level (e.g. `0.05`),
/// - `params[2]` = initial subset size as fraction of `n`.
///
/// Use [`SummaryStats::<f64>::bacon_default_params`] for sensible
/// defaults.
pub fn outliers_bacon(&mut self, params: &[T; 3]) -> Result<Vec<T>> {
let n_params: c_int = 3;
let mut weights = vec![T::default(); self._n];
let status = unsafe {
T::ss_edit_outliers_detection(
self.task,
&n_params,
params.as_ptr(),
weights.as_mut_ptr(),
)
};
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_OUTLIERS as u64,
sys::VSL_SS_METHOD_BACON as c_int,
)
};
check_vsl(status)?;
Ok(weights)
}
/// Imputed mean + covariance for data containing missing values
/// (marked as `NaN`). Runs MKL's multiple-imputation EM
/// estimator with the supplied `params` (length-5 vector;
/// `VSL_SS_MI_PARAMS_SIZE` in `onemkl-sys`).
///
/// Returns `(mean, cov)`. The simulated imputations themselves
/// are written into the *original* data buffer in-place where
/// supported by MKL — pass a mutable copy if you need to retain
/// the original.
///
/// Most callers should use
/// [`SummaryStats::<f64>::impute_default_params`] which supplies
/// a sensible default `params` array.
pub fn impute_missing(&mut self, params: &[T; 5]) -> Result<(Vec<T>, Vec<T>)> {
let n_params: c_int = 5;
let init_n: c_int = 0;
let prior_n: c_int = 0;
let simul_n: c_int = 0;
let estimates_n: c_int = (self.p + self.p * self.p) as c_int;
let mut estimates = vec![T::default(); self.p + self.p * self.p];
let status = unsafe {
T::ss_edit_missing_values(
self.task,
&n_params,
params.as_ptr(),
&init_n,
ptr::null(),
&prior_n,
ptr::null(),
&simul_n,
ptr::null_mut(),
&estimates_n,
estimates.as_mut_ptr(),
)
};
check_vsl(status)?;
let status = unsafe {
T::ss_compute(
self.task,
sys::VSL_SS_MISSING_VALS as u64,
sys::VSL_SS_METHOD_MI as c_int,
)
};
check_vsl(status)?;
let mean = estimates[..self.p].to_vec();
let cov = estimates[self.p..].to_vec();
Ok((mean, cov))
}
}
impl SummaryStats<'_, f64> {
/// Default BACON parameters: median initialization, α = 0.05,
/// β = 0.05.
#[inline]
#[must_use]
pub fn bacon_default_params() -> [f64; 3] {
[sys::VSL_SS_METHOD_BACON_MEDIAN_INIT as f64, 0.05, 0.05]
}
/// Default multiple-imputation parameters: copy input, 25 EM
/// iterations, 1e-4 stopping tolerance.
#[inline]
#[must_use]
pub fn impute_default_params() -> [f64; 5] {
[
sys::VSL_SS_METHOD_MI as f64, // method id
25.0, // max iterations
1.0e-4, // tolerance
1.0, // copy data flag
0.0, // reserved
]
}
}
impl SummaryStats<'_, f32> {
/// `f32` counterpart of [`SummaryStats::<f64>::bacon_default_params`].
#[inline]
#[must_use]
pub fn bacon_default_params() -> [f32; 3] {
[sys::VSL_SS_METHOD_BACON_MEDIAN_INIT as f32, 0.05, 0.05]
}
/// `f32` counterpart of [`SummaryStats::<f64>::impute_default_params`].
#[inline]
#[must_use]
pub fn impute_default_params() -> [f32; 5] {
[sys::VSL_SS_METHOD_MI as f32, 25.0, 1.0e-4, 1.0, 0.0]
}
}
impl<T: SsScalar> Drop for SummaryStats<'_, T> {
fn drop(&mut self) {
if !self.task.is_null() {
unsafe {
let _ = sys::vslSSDeleteTask(&mut self.task);
}
}
}
}
#[inline]
fn check_vsl(status: c_int) -> Result<()> {
if status == 0 {
Ok(())
} else {
Err(Error::PardisoStatus(status))
}
}