forked from rust-ndarray/ndarray
-
Notifications
You must be signed in to change notification settings - Fork 0
/
par_rayon.rs
88 lines (80 loc) · 2.5 KB
/
par_rayon.rs
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
#![cfg(feature = "rayon")]
use ndarray::parallel::prelude::*;
use ndarray::prelude::*;
const M: usize = 1024 * 10;
const N: usize = 100;
const CHUNK_SIZE: usize = 100;
const N_CHUNKS: usize = (M + CHUNK_SIZE - 1) / CHUNK_SIZE;
#[test]
fn test_axis_iter() {
let mut a = Array2::<f64>::zeros((M, N));
for (i, mut v) in a.axis_iter_mut(Axis(0)).enumerate() {
v.fill(i as _);
}
assert_eq!(a.axis_iter(Axis(0)).len(), M);
let s: f64 = a.axis_iter(Axis(0)).into_par_iter().map(|x| x.sum()).sum();
println!("{:?}", a.slice(s![..10, ..5]));
assert_eq!(s, a.sum());
}
#[test]
#[cfg(feature = "approx")]
fn test_axis_iter_mut() {
use approx::assert_abs_diff_eq;
let mut a = Array::linspace(0., 1.0f64, M * N)
.into_shape((M, N))
.unwrap();
let b = a.mapv(|x| x.exp());
a.axis_iter_mut(Axis(0))
.into_par_iter()
.for_each(|mut v| v.mapv_inplace(|x| x.exp()));
println!("{:?}", a.slice(s![..10, ..5]));
assert_abs_diff_eq!(a, b, epsilon = 0.001);
}
#[test]
fn test_regular_iter() {
let mut a = Array2::<f64>::zeros((M, N));
for (i, mut v) in a.axis_iter_mut(Axis(0)).enumerate() {
v.fill(i as _);
}
let s: f64 = a.view().into_par_iter().map(|&x| x).sum();
println!("{:?}", a.slice(s![..10, ..5]));
assert_eq!(s, a.sum());
}
#[test]
fn test_regular_iter_collect() {
let mut a = Array2::<f64>::zeros((M, N));
for (i, mut v) in a.axis_iter_mut(Axis(0)).enumerate() {
v.fill(i as _);
}
let v = a.view().into_par_iter().map(|&x| x).collect::<Vec<_>>();
assert_eq!(v.len(), a.len());
}
#[test]
fn test_axis_chunks_iter() {
let mut a = Array2::<f64>::zeros((M, N));
for (i, mut v) in a.axis_chunks_iter_mut(Axis(0), CHUNK_SIZE).enumerate() {
v.fill(i as _);
}
assert_eq!(a.axis_chunks_iter(Axis(0), CHUNK_SIZE).len(), N_CHUNKS);
let s: f64 = a
.axis_chunks_iter(Axis(0), CHUNK_SIZE)
.into_par_iter()
.map(|x| x.sum())
.sum();
println!("{:?}", a.slice(s![..10, ..5]));
assert_eq!(s, a.sum());
}
#[test]
#[cfg(feature = "approx")]
fn test_axis_chunks_iter_mut() {
use approx::assert_abs_diff_eq;
let mut a = Array::linspace(0., 1.0f64, M * N)
.into_shape((M, N))
.unwrap();
let b = a.mapv(|x| x.exp());
a.axis_chunks_iter_mut(Axis(0), CHUNK_SIZE)
.into_par_iter()
.for_each(|mut v| v.mapv_inplace(|x| x.exp()));
println!("{:?}", a.slice(s![..10, ..5]));
assert_abs_diff_eq!(a, b, epsilon = 0.001);
}