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
use super::SummaryStatisticsExt;
use crate::errors::{EmptyInput, MultiInputError, ShapeMismatch};
use ndarray::{Array, ArrayBase, Axis, Data, Dimension, Ix1, RemoveAxis};
use num_integer::IterBinomial;
use num_traits::{Float, FromPrimitive, Zero};
use std::ops::{Add, AddAssign, Div, Mul};
impl<A, S, D> SummaryStatisticsExt<A, S, D> for ArrayBase<S, D>
where
S: Data<Elem = A>,
D: Dimension,
{
fn mean(&self) -> Result<A, EmptyInput>
where
A: Clone + FromPrimitive + Add<Output = A> + Div<Output = A> + Zero,
{
let n_elements = self.len();
if n_elements == 0 {
Err(EmptyInput)
} else {
let n_elements = A::from_usize(n_elements)
.expect("Converting number of elements to `A` must not fail.");
Ok(self.sum() / n_elements)
}
}
fn weighted_mean(&self, weights: &Self) -> Result<A, MultiInputError>
where
A: Copy + Div<Output = A> + Mul<Output = A> + Zero,
{
return_err_if_empty!(self);
let weighted_sum = self.weighted_sum(weights)?;
Ok(weighted_sum / weights.sum())
}
fn weighted_sum(&self, weights: &ArrayBase<S, D>) -> Result<A, MultiInputError>
where
A: Copy + Mul<Output = A> + Zero,
{
return_err_unless_same_shape!(self, weights);
Ok(self
.iter()
.zip(weights)
.fold(A::zero(), |acc, (&d, &w)| acc + d * w))
}
fn weighted_mean_axis(
&self,
axis: Axis,
weights: &ArrayBase<S, Ix1>,
) -> Result<Array<A, D::Smaller>, MultiInputError>
where
A: Copy + Div<Output = A> + Mul<Output = A> + Zero,
D: RemoveAxis,
{
return_err_if_empty!(self);
let mut weighted_sum = self.weighted_sum_axis(axis, weights)?;
let weights_sum = weights.sum();
weighted_sum.mapv_inplace(|v| v / weights_sum);
Ok(weighted_sum)
}
fn weighted_sum_axis(
&self,
axis: Axis,
weights: &ArrayBase<S, Ix1>,
) -> Result<Array<A, D::Smaller>, MultiInputError>
where
A: Copy + Mul<Output = A> + Zero,
D: RemoveAxis,
{
if self.shape()[axis.index()] != weights.len() {
return Err(MultiInputError::ShapeMismatch(ShapeMismatch {
first_shape: self.shape().to_vec(),
second_shape: weights.shape().to_vec(),
}));
}
Ok(self.map_axis(axis, |lane| {
lane.iter()
.zip(weights)
.fold(A::zero(), |acc, (&d, &w)| acc + d * w)
}))
}
fn harmonic_mean(&self) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
{
self.map(|x| x.recip())
.mean()
.map(|x| x.recip())
.ok_or(EmptyInput)
}
fn geometric_mean(&self) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
{
self.map(|x| x.ln())
.mean()
.map(|x| x.exp())
.ok_or(EmptyInput)
}
fn weighted_var(&self, weights: &Self, ddof: A) -> Result<A, MultiInputError>
where
A: AddAssign + Float + FromPrimitive,
{
return_err_if_empty!(self);
return_err_unless_same_shape!(self, weights);
let zero = A::from_usize(0).expect("Converting 0 to `A` must not fail.");
let one = A::from_usize(1).expect("Converting 1 to `A` must not fail.");
assert!(
!(ddof < zero || ddof > one),
"`ddof` must not be less than zero or greater than one",
);
inner_weighted_var(self, weights, ddof, zero)
}
fn weighted_std(&self, weights: &Self, ddof: A) -> Result<A, MultiInputError>
where
A: AddAssign + Float + FromPrimitive,
{
Ok(self.weighted_var(weights, ddof)?.sqrt())
}
fn weighted_var_axis(
&self,
axis: Axis,
weights: &ArrayBase<S, Ix1>,
ddof: A,
) -> Result<Array<A, D::Smaller>, MultiInputError>
where
A: AddAssign + Float + FromPrimitive,
D: RemoveAxis,
{
return_err_if_empty!(self);
if self.shape()[axis.index()] != weights.len() {
return Err(MultiInputError::ShapeMismatch(ShapeMismatch {
first_shape: self.shape().to_vec(),
second_shape: weights.shape().to_vec(),
}));
}
let zero = A::from_usize(0).expect("Converting 0 to `A` must not fail.");
let one = A::from_usize(1).expect("Converting 1 to `A` must not fail.");
assert!(
!(ddof < zero || ddof > one),
"`ddof` must not be less than zero or greater than one",
);
let weights = weights.view();
Ok(self.map_axis(axis, |lane| {
inner_weighted_var(&lane, &weights, ddof, zero).unwrap()
}))
}
fn weighted_std_axis(
&self,
axis: Axis,
weights: &ArrayBase<S, Ix1>,
ddof: A,
) -> Result<Array<A, D::Smaller>, MultiInputError>
where
A: AddAssign + Float + FromPrimitive,
D: RemoveAxis,
{
Ok(self
.weighted_var_axis(axis, weights, ddof)?
.mapv_into(|x| x.sqrt()))
}
fn kurtosis(&self) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
{
let central_moments = self.central_moments(4)?;
Ok(central_moments[4] / central_moments[2].powi(2))
}
fn skewness(&self) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
{
let central_moments = self.central_moments(3)?;
Ok(central_moments[3] / central_moments[2].sqrt().powi(3))
}
fn central_moment(&self, order: u16) -> Result<A, EmptyInput>
where
A: Float + FromPrimitive,
{
if self.is_empty() {
return Err(EmptyInput);
}
match order {
0 => Ok(A::one()),
1 => Ok(A::zero()),
n => {
let mean = self.mean().unwrap();
let shifted_array = self.mapv(|x| x - mean);
let shifted_moments = moments(shifted_array, n);
let correction_term = -shifted_moments[1];
let coefficients = central_moment_coefficients(&shifted_moments);
Ok(horner_method(coefficients, correction_term))
}
}
}
fn central_moments(&self, order: u16) -> Result<Vec<A>, EmptyInput>
where
A: Float + FromPrimitive,
{
if self.is_empty() {
return Err(EmptyInput);
}
match order {
0 => Ok(vec![A::one()]),
1 => Ok(vec![A::one(), A::zero()]),
n => {
let mean = self.mean().unwrap();
let shifted_array = self.mapv(|x| x - mean);
let shifted_moments = moments(shifted_array, n);
let correction_term = -shifted_moments[1];
let mut central_moments = vec![A::one(), A::zero()];
for k in 2..=n {
let coefficients =
central_moment_coefficients(&shifted_moments[..=(k as usize)]);
let central_moment = horner_method(coefficients, correction_term);
central_moments.push(central_moment)
}
Ok(central_moments)
}
}
}
private_impl! {}
}
fn inner_weighted_var<A, S, D>(
arr: &ArrayBase<S, D>,
weights: &ArrayBase<S, D>,
ddof: A,
zero: A,
) -> Result<A, MultiInputError>
where
S: Data<Elem = A>,
A: AddAssign + Float + FromPrimitive,
D: Dimension,
{
let mut weight_sum = zero;
let mut mean = zero;
let mut s = zero;
for (&x, &w) in arr.iter().zip(weights.iter()) {
weight_sum += w;
let x_minus_mean = x - mean;
mean += (w / weight_sum) * x_minus_mean;
s += w * x_minus_mean * (x - mean);
}
Ok(s / (weight_sum - ddof))
}
fn moments<A, S, D>(a: ArrayBase<S, D>, order: u16) -> Vec<A>
where
A: Float + FromPrimitive,
S: Data<Elem = A>,
D: Dimension,
{
let n_elements =
A::from_usize(a.len()).expect("Converting number of elements to `A` must not fail");
let order = i32::from(order);
let mut moments = vec![A::one()];
if order >= 1 {
moments.push(a.sum() / n_elements)
}
for k in 2..=order {
moments.push(a.map(|x| x.powi(k)).sum() / n_elements)
}
moments
}
fn central_moment_coefficients<A>(moments: &[A]) -> Vec<A>
where
A: Float + FromPrimitive,
{
let order = moments.len();
IterBinomial::new(order)
.zip(moments.iter().rev())
.map(|(binom, &moment)| A::from_usize(binom).unwrap() * moment)
.collect()
}
fn horner_method<A>(coefficients: Vec<A>, indeterminate: A) -> A
where
A: Float,
{
let mut result = A::zero();
for coefficient in coefficients.into_iter().rev() {
result = coefficient + indeterminate * result
}
result
}