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
use crate::prelude::*;
use crate::utils::{CustomIterTools, NoNull};
use num::{Float, NumCast};
use rand::distributions::Bernoulli;
use rand::prelude::*;
use rand::seq::IteratorRandom;
use rand_distr::{Distribution, Normal, StandardNormal, Uniform};
fn create_rand_index_with_replacement(n: usize, len: usize) -> (ThreadRng, UInt32Chunked) {
let mut rng = rand::thread_rng();
(
rng,
(0u32..n as u32)
.map(move |_| Uniform::new(0u32, len as u32).sample(&mut rng))
.collect_trusted::<NoNull<UInt32Chunked>>()
.into_inner(),
)
}
fn create_rand_index_no_replacement(n: usize, len: usize) -> (ThreadRng, UInt32Chunked) {
let mut rng = rand::thread_rng();
let mut buf = AlignedVec::with_capacity(n);
unsafe { buf.set_len(n) };
(0u32..len as u32).choose_multiple_fill(&mut rng, buf.as_mut_slice());
(rng, UInt32Chunked::new_from_aligned_vec("", buf))
}
impl<T> ChunkedArray<T>
where
ChunkedArray<T>: ChunkTake,
{
pub fn sample_n(&self, n: usize, with_replacement: bool) -> Result<Self> {
if !with_replacement && n > self.len() {
return Err(PolarsError::ShapeMisMatch(
"n is larger than the number of elements in this array".into(),
));
}
let len = self.len();
match with_replacement {
true => {
let (_, idx) = create_rand_index_with_replacement(n, len);
debug_assert_eq!(len, self.len());
unsafe { Ok(self.take_unchecked((&idx).into())) }
}
false => {
let (_, idx) = create_rand_index_no_replacement(n, len);
debug_assert_eq!(len, self.len());
unsafe { Ok(self.take_unchecked((&idx).into())) }
}
}
}
pub fn sample_frac(&self, frac: f64, with_replacement: bool) -> Result<Self> {
let n = (self.len() as f64 * frac) as usize;
self.sample_n(n, with_replacement)
}
}
impl DataFrame {
pub fn sample_n(&self, n: usize, with_replacement: bool) -> Result<Self> {
if !with_replacement && n > self.height() {
return Err(PolarsError::ShapeMisMatch(
"n is larger than the number of elements in this array".into(),
));
}
let idx: UInt32Chunked = match with_replacement {
true => create_rand_index_with_replacement(n, self.height()).1,
false => create_rand_index_no_replacement(n, self.height()).1,
};
Ok(unsafe { self.take_unchecked(&idx) })
}
pub fn sample_frac(&self, frac: f64, with_replacement: bool) -> Result<Self> {
let n = (self.height() as f64 * frac) as usize;
self.sample_n(n, with_replacement)
}
}
impl<T> ChunkedArray<T>
where
T: PolarsNumericType,
T::Native: Float,
{
pub fn rand_normal(name: &str, length: usize, mean: f64, std_dev: f64) -> Result<Self> {
let normal = match Normal::new(mean, std_dev) {
Ok(dist) => dist,
Err(e) => return Err(PolarsError::RandError(format!("{:?}", e))),
};
let mut builder = PrimitiveChunkedBuilder::<T>::new(name, length);
let mut rng = rand::thread_rng();
for _ in 0..length {
let smpl = normal.sample(&mut rng);
let smpl = NumCast::from(smpl).unwrap();
builder.append_value(smpl)
}
Ok(builder.finish())
}
pub fn rand_standard_normal(name: &str, length: usize) -> Self {
let mut builder = PrimitiveChunkedBuilder::<T>::new(name, length);
let mut rng = rand::thread_rng();
for _ in 0..length {
let smpl: f64 = rng.sample(StandardNormal);
let smpl = NumCast::from(smpl).unwrap();
builder.append_value(smpl)
}
builder.finish()
}
pub fn rand_uniform(name: &str, length: usize, low: f64, high: f64) -> Self {
let uniform = Uniform::new(low, high);
let mut builder = PrimitiveChunkedBuilder::<T>::new(name, length);
let mut rng = rand::thread_rng();
for _ in 0..length {
let smpl = uniform.sample(&mut rng);
let smpl = NumCast::from(smpl).unwrap();
builder.append_value(smpl)
}
builder.finish()
}
}
impl BooleanChunked {
pub fn rand_bernoulli(name: &str, length: usize, p: f64) -> Result<Self> {
let dist = match Bernoulli::new(p) {
Ok(dist) => dist,
Err(e) => return Err(PolarsError::RandError(format!("{:?}", e))),
};
let mut rng = rand::thread_rng();
let mut builder = BooleanChunkedBuilder::new(name, length);
for _ in 0..length {
let smpl = dist.sample(&mut rng);
builder.append_value(smpl)
}
Ok(builder.finish())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_sample() {
let df = df![
"foo" => &[1, 2, 3, 4, 5]
]
.unwrap();
assert!(df.sample_n(3, false).is_ok());
assert!(df.sample_frac(0.4, false).is_ok());
assert!(df.sample_frac(2.0, false).is_err());
assert!(df.sample_n(3, true).is_ok());
assert!(df.sample_frac(0.4, true).is_ok());
assert!(df.sample_frac(2.0, true).is_ok());
}
}