random_constructible/
lib.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
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
#![allow(unused_imports)]
use rand::distributions::Distribution;
use rand::prelude::SliceRandom;
use rand::Rng;
use std::hash::Hash;
use once_cell::sync::Lazy;
use std::sync::Arc;
use std::collections::HashMap;

pub trait RandomConstructible {
    fn random() -> Self;
    fn uniform() -> Self;
}

impl<E: RandomConstructibleEnum> RandomConstructible for E {

    fn random() -> Self {
        <Self as RandomConstructibleEnum>::random_variant()
    }

    fn uniform() -> Self {
        <Self as RandomConstructibleEnum>::uniform_variant()
    }
}

pub trait RandomConstructibleEnum: Default + Eq + Hash + Sized + Copy {

    //-----------------------------------------------------------------[provided by the proc macro crate]
    fn default_weight(&self) -> f64;

    fn all_variants() -> Vec<Self>;

    // this is implemented in the proc macro so that we by default get once_cell behavior
    fn create_default_probability_map() -> Arc<HashMap<Self,f64>>;

    //-----------------------------------------------------------------[main user-interface]
    fn random_variant() -> Self {
        let map = Self::create_default_probability_map();
        let mut rng = rand::thread_rng();
        Self::sample_with_probabilities(&mut rng, &map)
    }

    fn uniform_variant() -> Self {
        let variants = Self::all_variants();
        let mut rng = rand::thread_rng();
        *variants.choose(&mut rng).unwrap()
    }

    fn random_with_provider<P: RandomConstructibleProbabilityMapProvider<Self>>() -> Self {
        let mut rng = rand::thread_rng();
        Self::sample_from_provider::<P,_>(&mut rng)
    }

    fn random_uniform_with_provider<P: RandomConstructibleProbabilityMapProvider<Self>>() -> Self {
        let mut rng = rand::thread_rng();
        Self::sample_uniformly_from_provider::<P,_>(&mut rng)
    }

    //-----------------------------------------------------------------[helper-methods]
    fn sample_with_probabilities<RNG: Rng + ?Sized>(rng: &mut RNG, probs: &HashMap<Self,f64>) -> Self {
        let variants: Vec<_> = probs.keys().cloned().collect();
        let weights:  Vec<_> = variants.iter().map(|v| probs[v]).collect();
        let dist = rand::distributions::WeightedIndex::new(&weights).unwrap();
        variants[dist.sample(rng)]
    }

    // Helper function to sample from a provider using the given RNG
    fn sample_from_provider<P: RandomConstructibleProbabilityMapProvider<Self>, RNG: Rng + ?Sized>(rng: &mut RNG) -> Self {
        let probs = P::probability_map();
        Self::sample_with_probabilities(rng,&probs)
    }

    fn sample_uniformly_from_provider<P: RandomConstructibleProbabilityMapProvider<Self>, RNG: Rng + ?Sized>(rng: &mut RNG) -> Self {
        let probs = P::uniform_probability_map();
        Self::sample_with_probabilities(rng,&probs)
    }

    fn random_with_rng<RNG: Rng + ?Sized>(rng: &mut RNG) -> Self {
        let map = Self::create_default_probability_map();
        Self::sample_with_probabilities(rng, &map)
    }
}

pub trait RandomConstructibleProbabilityMapProvider<R: RandomConstructibleEnum> {
    fn probability_map() -> Arc<HashMap<R, f64>>;
    fn uniform_probability_map() -> Arc<HashMap<R, f64>>;
}

pub trait RandomConstructibleEnvironment {
    fn create_random<R>() -> R
    where
        R: RandomConstructibleEnum,
        Self: RandomConstructibleProbabilityMapProvider<R> + Sized,
    {
        R::random_with_provider::<Self>()
    }

    fn create_random_uniform<R>() -> R
    where
        R: RandomConstructibleEnum,
        Self: RandomConstructibleProbabilityMapProvider<R> + Sized,
    {
        R::random_uniform_with_provider::<Self>()
    }
}

#[macro_export]
macro_rules! random_constructible_probability_map_provider {
    ($provider:ident => $enum:ty { $($variant:ident => $weight:expr),* $(,)? }) => {
        impl $crate::RandomConstructibleProbabilityMapProvider<$enum> for $provider {
            fn probability_map() -> std::sync::Arc<std::collections::HashMap<$enum, f64>> {
                use once_cell::sync::Lazy;
                static PROBABILITY_MAP: Lazy<std::sync::Arc<std::collections::HashMap<$enum, f64>>> = Lazy::new(|| {
                    let mut map = std::collections::HashMap::new();
                    $(
                        map.insert(<$enum>::$variant, $weight);
                    )*
                    std::sync::Arc::new(map)
                });
                std::sync::Arc::clone(&PROBABILITY_MAP)
            }

            fn uniform_probability_map() -> std::sync::Arc<std::collections::HashMap<$enum, f64>> {
                use once_cell::sync::Lazy;
                static UNIFORM_PROBABILITY_MAP: Lazy<std::sync::Arc<std::collections::HashMap<$enum, f64>>> = Lazy::new(|| {
                    let mut map = std::collections::HashMap::new();
                    $(
                        map.insert(<$enum>::$variant, 1.0);
                    )*
                    std::sync::Arc::new(map)
                });
                std::sync::Arc::clone(&UNIFORM_PROBABILITY_MAP)
            }
        }
    };
}

#[cfg(test)]
mod tests {
    use super::*;
    use rand::rngs::StdRng;
    use rand::SeedableRng;
    use std::collections::HashMap;
    use std::sync::Arc;

    // Define a test enum and manually implement RandomConstructibleEnum
    #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
    enum ManualTestEnum {
        VariantX,
        VariantY,
        VariantZ,
    }

    impl Default for ManualTestEnum {
        fn default() -> Self {
            Self::VariantX
        }
    }

    impl RandomConstructibleEnum for ManualTestEnum {
        fn all_variants() -> Vec<Self> {
            vec![Self::VariantX, Self::VariantY, Self::VariantZ]
        }

        fn default_weight(&self) -> f64 {
            match self {
                Self::VariantX => 2.0,
                Self::VariantY => 3.0,
                Self::VariantZ => 5.0,
            }
        }

        fn create_default_probability_map() -> Arc<HashMap<Self, f64>> {
            DefaultProvider::probability_map()
        }
    }

    // Implement the default provider using the macro
    struct DefaultProvider;

    random_constructible_probability_map_provider!(DefaultProvider => ManualTestEnum {
        VariantX => 2.0,
        VariantY => 3.0,
        VariantZ => 5.0,
    });

    // Implement a custom probability provider using the macro
    struct CustomProvider;

    random_constructible_probability_map_provider!(CustomProvider => ManualTestEnum {
        VariantX => 1.0,
        VariantY => 1.0,
        VariantZ => 8.0,
    });

    #[test]
    fn test_manual_all_variants() {
        let variants = ManualTestEnum::all_variants();
        assert_eq!(variants.len(), 3);
        assert!(variants.contains(&ManualTestEnum::VariantX));
        assert!(variants.contains(&ManualTestEnum::VariantY));
        assert!(variants.contains(&ManualTestEnum::VariantZ));
    }

    #[test]
    fn test_manual_default_weight() {
        assert_eq!(ManualTestEnum::VariantX.default_weight(), 2.0);
        assert_eq!(ManualTestEnum::VariantY.default_weight(), 3.0);
        assert_eq!(ManualTestEnum::VariantZ.default_weight(), 5.0);
    }

    #[test]
    fn test_manual_random() {
        let mut rng = StdRng::seed_from_u64(42);
        let mut counts = HashMap::new();

        for _ in 0..10000 {
            let variant = ManualTestEnum::random_with_rng(&mut rng);
            *counts.entry(variant).or_insert(0) += 1;
        }

        let total = counts.values().sum::<usize>() as f64;
        let prob_x = *counts.get(&ManualTestEnum::VariantX).unwrap_or(&0) as f64 / total;
        let prob_y = *counts.get(&ManualTestEnum::VariantY).unwrap_or(&0) as f64 / total;
        let prob_z = *counts.get(&ManualTestEnum::VariantZ).unwrap_or(&0) as f64 / total;

        // Expected probabilities: X: 0.2, Y: 0.3, Z: 0.5
        assert!((prob_x - 0.2).abs() < 0.05);
        assert!((prob_y - 0.3).abs() < 0.05);
        assert!((prob_z - 0.5).abs() < 0.05);
    }

    #[test]
    fn test_manual_uniform() {
        let mut counts = HashMap::new();

        for _ in 0..10000 {
            let variant = ManualTestEnum::uniform();
            *counts.entry(variant).or_insert(0) += 1;
        }

        let total = counts.values().sum::<usize>() as f64;
        for &count in counts.values() {
            let prob = count as f64 / total;
            assert!((prob - (1.0 / 3.0)).abs() < 0.05);
        }
    }

    #[test]
    fn test_manual_random_with_probabilities() {
        let mut rng = StdRng::seed_from_u64(42);
        let probs = CustomProvider::probability_map();

        let mut counts = HashMap::new();

        for _ in 0..10000 {
            let variant = ManualTestEnum::sample_with_probabilities(&mut rng, &probs);
            *counts.entry(variant).or_insert(0) += 1;
        }

        // Expected probabilities: X: 0.1, Y: 0.1, Z: 0.8
        let total = counts.values().sum::<usize>() as f64;
        let prob_x = *counts.get(&ManualTestEnum::VariantX).unwrap_or(&0) as f64 / total;
        let prob_y = *counts.get(&ManualTestEnum::VariantY).unwrap_or(&0) as f64 / total;
        let prob_z = *counts.get(&ManualTestEnum::VariantZ).unwrap_or(&0) as f64 / total;

        assert!((prob_x - 0.1).abs() < 0.02);
        assert!((prob_y - 0.1).abs() < 0.02);
        assert!((prob_z - 0.8).abs() < 0.05);
    }

    #[test]
    fn test_manual_sample_from_provider() {
        let mut rng = StdRng::seed_from_u64(42);
        let mut counts = HashMap::new();

        for _ in 0..10000 {
            let variant = ManualTestEnum::sample_from_provider::<CustomProvider, _>(&mut rng);
            *counts.entry(variant).or_insert(0) += 1;
        }

        // Expected probabilities: X: 0.1, Y: 0.1, Z: 0.8
        let total = counts.values().sum::<usize>() as f64;
        let prob_x = *counts.get(&ManualTestEnum::VariantX).unwrap_or(&0) as f64 / total;
        let prob_y = *counts.get(&ManualTestEnum::VariantY).unwrap_or(&0) as f64 / total;
        let prob_z = *counts.get(&ManualTestEnum::VariantZ).unwrap_or(&0) as f64 / total;

        assert!((prob_x - 0.1).abs() < 0.02);
        assert!((prob_y - 0.1).abs() < 0.02);
        assert!((prob_z - 0.8).abs() < 0.05);
    }
}