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
//! Small statistics reductions (RFC-040).
//!
//! [`Tensor::var`] / [`Tensor::std`] compute the **population** variance and
//! standard deviation over all elements; [`Tensor::var_axis`] / [`Tensor::std_axis`]
//! do the same along one axis (removing it from the output shape). These are the
//! only statistics in core — quantile, percentile, histogram, covariance,
//! correlation, and z-score are deferred to a possible future `matten-stats`
//! companion (RFC-040 §6/§8), and there is no sample-variance (`ddof = 1`) variant
//! in the first cut.
//!
//! **Variance is population variance, not sample variance:**
//! `var = sum((x_i - mean)^2) / n` and `std = sqrt(var)`. A two-pass algorithm is
//! used (mean first, then squared deviations) to avoid the avoidable cancellation
//! of the naive one-pass `E[x^2] - E[x]^2`. `NaN` propagates (any `NaN` element
//! yields `NaN`), consistent with the other `f64` reductions.
use crate::{MattenError, Tensor};
/// Population variance of a non-empty slice, two-pass: `sum((x - mean)^2) / n`.
/// Callers guarantee `data` is non-empty.
fn population_variance(data: &[f64]) -> f64 {
let n = data.len() as f64;
let mean = data.iter().sum::<f64>() / n;
data.iter()
.map(|x| {
let d = x - mean;
d * d
})
.sum::<f64>()
/ n
}
/// Population variance reduced along `axis`, removing that axis (two-pass per
/// slice). Shared by [`Tensor::try_var_axis`] and [`Tensor::try_std_axis`].
fn variance_axis_impl(
t: &Tensor,
axis: usize,
operation: &'static str,
) -> Result<Tensor, MattenError> {
crate::math::reject_dynamic(t, operation)?;
let rank = t.shape.len();
if axis >= rank {
return Err(MattenError::Shape {
operation,
message: format!("axis {axis} is out of range for a rank-{rank} tensor"),
});
}
let axis_len = t.shape[axis];
let outer: usize = t.shape[..axis].iter().product();
let inner: usize = t.shape[axis + 1..].iter().product();
let mut data = Vec::with_capacity(outer * inner);
for o in 0..outer {
let base = o * axis_len * inner;
for i in 0..inner {
// Two-pass over the `axis_len` values at stride `inner`.
let mut sum = 0.0;
for a in 0..axis_len {
sum += t.data[base + a * inner + i];
}
let mean = sum / axis_len as f64;
let mut acc = 0.0;
for a in 0..axis_len {
let d = t.data[base + a * inner + i] - mean;
acc += d * d;
}
data.push(acc / axis_len as f64);
}
}
let out_shape: Vec<usize> = t.shape[..axis]
.iter()
.chain(&t.shape[axis + 1..])
.copied()
.collect();
Ok(Tensor {
data,
shape: out_shape,
#[cfg(feature = "dynamic")]
dynamic: None,
})
}
impl Tensor {
/// Population variance over all elements: `sum((x_i - mean)^2) / n`.
///
/// This is **population** variance (`ddof = 0`), not sample variance — it
/// divides by `n`, not `n - 1`. A single-element tensor has variance `0.0`.
/// `NaN` propagates.
///
/// # Panics
/// Panics on a dynamic tensor (call [`try_numeric`](crate::Tensor::try_numeric)
/// first). Use [`Tensor::try_var`] for the non-panicking form.
///
/// ```
/// use matten::Tensor;
/// // [1,2,3,4]: mean 2.5, population variance 1.25
/// assert_eq!(Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0]).var(), 1.25);
/// ```
#[must_use]
pub fn var(&self) -> f64 {
self.try_var().unwrap_or_else(|e| panic!("{e}"))
}
/// Non-panicking [`Tensor::var`].
///
/// # Errors
/// Returns [`MattenError::Unsupported`] on a dynamic tensor, or
/// [`MattenError::InvalidArgument`] if the tensor is empty (RFC-105) —
/// reachable via slicing (`t.slice().range(0..0).all().build()`) and,
/// since RFC-111, directly via any constructor as well.
///
/// ```
/// use matten::Tensor;
/// assert_eq!(Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0]).try_var().unwrap(), 1.25);
/// ```
pub fn try_var(&self) -> Result<f64, MattenError> {
crate::math::reject_dynamic(self, "var")?;
if self.data.is_empty() {
return Err(MattenError::InvalidArgument {
operation: "var",
argument: "self",
message: "variance is undefined for an empty tensor".to_string(),
});
}
Ok(population_variance(&self.data))
}
/// Population standard deviation over all elements: `sqrt(var)`.
///
/// Population (`ddof = 0`), not sample. A single-element tensor has std `0.0`.
/// `NaN` propagates.
///
/// # Panics
/// Panics on a dynamic tensor. Use [`Tensor::try_std`] for the non-panicking
/// form.
///
/// ```
/// use matten::Tensor;
/// let s = Tensor::from_vec(vec![1.0, 2.0, 3.0, 4.0]).std();
/// assert!((s - 1.25_f64.sqrt()).abs() < 1e-12);
/// ```
#[must_use]
pub fn std(&self) -> f64 {
self.try_std().unwrap_or_else(|e| panic!("{e}"))
}
/// Non-panicking [`Tensor::std`].
///
/// # Errors
/// Returns [`MattenError::Unsupported`] on a dynamic tensor (and
/// [`MattenError::InvalidArgument`] on the unreachable empty-tensor case).
///
/// ```
/// use matten::Tensor;
/// assert!(Tensor::from_vec(vec![5.0]).try_std().unwrap() == 0.0);
/// ```
pub fn try_std(&self) -> Result<f64, MattenError> {
crate::math::reject_dynamic(self, "std")?;
if self.data.is_empty() {
return Err(MattenError::InvalidArgument {
operation: "std",
argument: "self",
message: "standard deviation is undefined for an empty tensor".to_string(),
});
}
Ok(population_variance(&self.data).sqrt())
}
/// Population variance along `axis`, removing that axis from the output shape.
///
/// Population (`ddof = 0`). `NaN` propagates within each reduced slice. No
/// `keepdims` (e.g. `[2, 3]` axis 0 → `[3]`, axis 1 → `[2]`).
///
/// # Panics
/// Panics if `axis >= rank`, on a dynamic tensor, or if the **reduced**
/// axis has length 0 (RFC-110) — the variance of nothing is undefined,
/// not `NaN`. A zero-length axis that *survives* the reduction yields an
/// empty result, not a panic. Use [`Tensor::try_var_axis`] for the
/// non-panicking form.
///
/// ```
/// use matten::Tensor;
/// let m = Tensor::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
/// assert_eq!(m.var_axis(0).as_slice(), &[2.25, 2.25, 2.25]);
/// ```
#[must_use]
pub fn var_axis(&self, axis: usize) -> Tensor {
self.try_var_axis(axis).unwrap_or_else(|e| panic!("{e}"))
}
/// Non-panicking [`Tensor::var_axis`].
///
/// # Errors
/// Returns [`MattenError::Shape`] if `axis >= rank`,
/// [`MattenError::Unsupported`] on a dynamic tensor, or
/// [`MattenError::InvalidArgument`] if the **reduced** axis has length 0
/// (RFC-110). A zero-length axis that *survives* the reduction still
/// returns `Ok` with an empty result.
///
/// ```
/// use matten::Tensor;
/// let m = Tensor::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
/// assert!(m.try_var_axis(2).is_err()); // axis out of range
/// ```
pub fn try_var_axis(&self, axis: usize) -> Result<Tensor, MattenError> {
crate::math::reject_dynamic(self, "var_axis")?;
if self.shape().get(axis) == Some(&0) {
return Err(MattenError::InvalidArgument {
operation: "var_axis",
argument: "axis",
message: format!(
"variance is undefined for a reduced axis of length 0 (axis {axis})"
),
});
}
variance_axis_impl(self, axis, "var_axis")
}
/// Population standard deviation along `axis`, removing that axis.
///
/// Population (`ddof = 0`). `NaN` propagates within each reduced slice.
///
/// # Panics
/// Panics if `axis >= rank`, on a dynamic tensor, or if the **reduced**
/// axis has length 0 (RFC-110) — the standard deviation of nothing is
/// undefined, not `NaN`. A zero-length axis that *survives* the
/// reduction yields an empty result, not a panic. Use
/// [`Tensor::try_std_axis`] for the non-panicking form.
///
/// ```
/// use matten::Tensor;
/// let m = Tensor::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
/// // each column [1,4],[2,5],[3,6] has variance 2.25, std 1.5
/// assert_eq!(m.std_axis(0).as_slice(), &[1.5, 1.5, 1.5]);
/// ```
#[must_use]
pub fn std_axis(&self, axis: usize) -> Tensor {
self.try_std_axis(axis).unwrap_or_else(|e| panic!("{e}"))
}
/// Non-panicking [`Tensor::std_axis`].
///
/// # Errors
/// Returns [`MattenError::Shape`] if `axis >= rank`,
/// [`MattenError::Unsupported`] on a dynamic tensor, or
/// [`MattenError::InvalidArgument`] if the **reduced** axis has length 0
/// (RFC-110). A zero-length axis that *survives* the reduction still
/// returns `Ok` with an empty result.
///
/// ```
/// use matten::Tensor;
/// let m = Tensor::new(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0], &[2, 3]);
/// assert!(m.try_std_axis(5).is_err());
/// ```
pub fn try_std_axis(&self, axis: usize) -> Result<Tensor, MattenError> {
crate::math::reject_dynamic(self, "std_axis")?;
if self.shape().get(axis) == Some(&0) {
return Err(MattenError::InvalidArgument {
operation: "std_axis",
argument: "axis",
message: format!(
"standard deviation is undefined for a reduced axis of length 0 (axis {axis})"
),
});
}
let mut v = variance_axis_impl(self, axis, "std_axis")?;
for x in &mut v.data {
*x = x.sqrt();
}
Ok(v)
}
}
#[cfg(test)]
mod tests;