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
use std::cell::RefCell;
use dry::macro_for;
use rand::{Rng, SeedableRng};
use crate::{
estimators::{CPDEstimator, MLE},
inference::Modelled,
models::{BN, CatBN, GaussBN, Labelled},
samplers::{BNSampler, ForwardSampler, ImportanceSampler, ParBNSampler},
types::Set,
};
/// An approximate inference engine.
#[derive(Debug)]
pub struct ApproximateInference<'a, R, M, E> {
rng: RefCell<&'a mut R>,
model: &'a M,
evidence: Option<&'a E>,
sample_size: Option<usize>,
}
impl<'a, R, M> ApproximateInference<'a, R, M, ()> {
/// Construct a new approximate inference instance.
///
/// # Arguments
///
/// * `rng` - A random number generator.
/// * `model` - A reference to the model to sample from.
///
/// # Returns
///
/// Return a new approximate inference instance.
///
#[inline]
pub const fn new(rng: &'a mut R, model: &'a M) -> Self {
// Wrap the RNG in a RefCell.
let rng = RefCell::new(rng);
Self {
rng,
model,
evidence: None,
sample_size: None,
}
}
}
impl<'a, R, M, E> ApproximateInference<'a, R, M, E> {
/// Add evidence to the approximate inference instance.
///
/// # Arguments
///
/// * `evidence` - A reference to the evidence.
///
/// # Returns
///
/// Return a new approximate inference instance with evidence.
///
#[inline]
pub const fn with_evidence<T>(self, evidence: &'a T) -> ApproximateInference<'a, R, M, T> {
ApproximateInference {
rng: self.rng,
model: self.model,
evidence: Some(evidence),
sample_size: self.sample_size,
}
}
/// Set the sample size for the approximate inference instance.
///
/// # Arguments
///
/// * `n` - The sample size.
///
/// # Panics
///
/// * Panics if `n` is zero.
///
/// # Returns
///
/// Return a new approximate inference instance with the specified sample size.
///
#[inline]
pub const fn with_sample_size(mut self, n: usize) -> Self {
// Assert the sample size is positive.
assert!(n > 0, "Sample size must be positive.");
// Set the sample size.
self.sample_size = Some(n);
self
}
}
impl<R, M, E> Modelled<M> for ApproximateInference<'_, R, M, E> {
#[inline]
fn model(&self) -> &M {
self.model
}
}
/// A trait for inference with Bayesian Networks.
pub trait BNInference<T>
where
T: BN,
{
/// Estimate the values of `x` conditioned on `z` using `n` samples.
///
/// # Arguments
///
/// * `x` - The set of variables.
/// * `z` - The set of conditioning variables.
///
/// # Panics
///
/// * Panics if `x` is empty.
/// * Panics if `x` and `z` are not disjoint.
/// * Panics if `x` or `z` are not in the model.
///
/// # Returns
///
/// The estimated values of `x` conditioned on `z`.
///
fn estimate(&self, x: &Set<usize>, z: &Set<usize>) -> T::CPD;
}
impl<'a, R, E> ApproximateInference<'a, R, CatBN, E> {
#[inline]
fn sample_size(&self, x: &Set<usize>, z: &Set<usize>) -> usize {
// Get the sample size or compute it if not provided.
self.sample_size.unwrap_or_else(|| {
// Get the shape of the variables X and Z.
let (x_shape, z_shape): (usize, usize) = (
x.iter().map(|&i| self.model.shape()[i]).product(),
z.iter().map(|&i| self.model.shape()[i]).product(),
);
// Return the sample size as PAC-like bounds:
// (|Z| * (|X| - 1)) * ln(1 / delta) / epsilon^2, or approximately
// (|Z| * (|X| - 1)) * 1200 for delta = 0.05 and epsilon = 0.05.
z_shape * (x_shape - 1) * 1200
})
}
}
impl<'a, R, E> ApproximateInference<'a, R, GaussBN, E> {
#[inline]
fn sample_size(&self, x: &Set<usize>, z: &Set<usize>) -> usize {
// Get the sample size or compute it if not provided.
self.sample_size.unwrap_or_else(|| {
// Get the shape of the variables X and Z.
let (x_shape, z_shape) = (x.len(), z.len());
// Return the sample size as PAC-like bounds:
// (|X| * |Z| + (|X| * (|X| + 1)) / 2) * ln(1 / delta) / epsilon^2, or approximately
// (|X| * |Z| + (|X| * (|X| + 1)) / 2) * 1200, for delta = 0.05 and epsilon = 0.05.
// |X| * (|Z| + (|X| + 1) / 2) * 1200, for delta = 0.05 and epsilon = 0.05.
x_shape * (z_shape + x_shape.div_ceil(2)) * 1200
})
}
}
macro_for!($type in [CatBN, GaussBN] {
impl<R: Rng> BNInference<$type> for ApproximateInference<'_, R, $type, ()> {
fn estimate(&self, x: &Set<usize>, z: &Set<usize>) -> <$type as BN>::CPD {
// Assert X is not empty.
assert!(!x.is_empty(), "Variables X must not be empty.");
// Assert X and Z are disjoint.
assert!(x.is_disjoint(z), "Variables X and Z must be disjoint.");
// Assert X and Z are in the model.
assert!(
x.union(z).all(|&i| i < self.model.labels().len()),
"Variables X and Z must be in the model."
);
// Get the sample size.
let n = self.sample_size(x, z);
// Get the RNG.
let mut rng = self.rng.borrow_mut();
// Initialize the sampler.
let sampler = ForwardSampler::new(&mut rng, self.model);
// Generate n samples from the model.
// TODO: Avoid generating the full dataset,
// e.g., by only sampling the variables in X U Z, and
// by using batching to reduce memory usage.
let dataset = sampler.sample_n(n);
// Initialize the estimator.
let estimator = MLE::new(&dataset);
// Fit the CPD.
estimator.fit(x, z)
}
}
impl<R: Rng> BNInference<$type> for ApproximateInference<'_, R, $type, <$type as BN>::Evidence> {
fn estimate(&self, x: &Set<usize>, z: &Set<usize>) -> <$type as BN>::CPD {
// Assert X is not empty.
assert!(!x.is_empty(), "Variables X must not be empty.");
// Assert X and Z are disjoint.
assert!(x.is_disjoint(z), "Variables X and Z must be disjoint.");
// Assert X and Z are in the model.
assert!(
x.union(z).all(|&i| i < self.model.labels().len()),
"Variables X and Z must be in the model."
);
// Get the sample size.
let n = self.sample_size(x, z);
// Get the RNG.
let mut rng = self.rng.borrow_mut();
// Check if evidence is actually provided.
match self.evidence {
// Get the evidence.
Some(evidence) => {
// Initialize the sampler.
let sampler = ImportanceSampler::new(&mut rng, self.model, evidence);
// Generate n samples from the model.
// TODO: Avoid generating the full dataset,
// e.g., by only sampling the variables in X U Z, and
// by using batching to reduce memory usage.
let dataset = sampler.sample_n(n);
// Initialize the estimator.
let estimator = MLE::new(&dataset);
// Fit the CPD.
estimator.fit(x, z)
}
// Delegate to empty evidence case.
None => ApproximateInference::new(&mut rng, self.model)
.with_sample_size(n)
.estimate(x, z),
}
}
}
});
/// A trait for parallel inference with Bayesian Networks.
pub trait ParBNInference<T>
where
T: BN,
{
/// Estimate the values of `x` conditioned on `z` using `n` samples, in parallel.
///
/// # Arguments
///
/// * `x` - The set of variables.
/// * `z` - The set of conditioning variables.
///
/// # Panics
///
/// * Panics if `x` is empty.
/// * Panics if `x` and `z` are not disjoint.
/// * Panics if `x` or `z` are not in the model.
///
/// # Returns
///
/// The estimated values of `x` conditioned on `z`.
///
fn par_estimate(&self, x: &Set<usize>, z: &Set<usize>) -> T::CPD;
}
macro_for!($type in [CatBN, GaussBN] {
impl<R: Rng + SeedableRng> ParBNInference<$type> for ApproximateInference<'_, R, $type, ()> {
fn par_estimate(&self, x: &Set<usize>, z: &Set<usize>) -> <$type as BN>::CPD {
// Assert X is not empty.
assert!(!x.is_empty(), "Variables X must not be empty.");
// Assert X and Z are disjoint.
assert!(x.is_disjoint(z), "Variables X and Z must be disjoint.");
// Assert X and Z are in the model.
assert!(
x.union(z).all(|&i| i < self.model.labels().len()),
"Variables X and Z must be in the model."
);
// Get the sample size.
let n = self.sample_size(x, z);
// Get the RNG.
let mut rng = self.rng.borrow_mut();
// Initialize the sampler.
let sampler = ForwardSampler::<R, _>::new(&mut rng, self.model);
// Generate n samples from the model.
// TODO: Avoid generating the full dataset,
// e.g., by only sampling the variables in X U Z, and
// by using batching to reduce memory usage.
let dataset = sampler.par_sample_n(n);
// Initialize the estimator.
let estimator = MLE::new(&dataset);
// Fit the CPD.
estimator.fit(x, z)
}
}
impl<R: Rng + SeedableRng> ParBNInference<$type> for ApproximateInference<'_, R, $type, <$type as BN>::Evidence> {
fn par_estimate(&self, x: &Set<usize>, z: &Set<usize>) -> <$type as BN>::CPD {
// Assert X is not empty.
assert!(!x.is_empty(), "Variables X must not be empty.");
// Assert X and Z are disjoint.
assert!(x.is_disjoint(z), "Variables X and Z must be disjoint.");
// Assert X and Z are in the model.
assert!(
x.union(z).all(|&i| i < self.model.labels().len()),
"Variables X and Z must be in the model."
);
// Get the sample size.
let n = self.sample_size(x, z);
// Get the RNG.
let mut rng = self.rng.borrow_mut();
// Check if evidence is actually provided.
match self.evidence {
// Get the evidence.
Some(evidence) => {
// Initialize the sampler.
let sampler = ImportanceSampler::<R, _, _>::new(&mut rng, self.model, evidence);
// Generate n samples from the model.
// TODO: Avoid generating the full dataset,
// e.g., by only sampling the variables in X U Z, and
// by using batching to reduce memory usage.
let dataset = sampler.par_sample_n(n);
// Initialize the estimator.
let estimator = MLE::new(&dataset);
// Fit the CPD.
estimator.fit(x, z)
}
// Delegate to empty evidence case.
None => ApproximateInference::new(&mut rng, self.model)
.with_sample_size(n)
.estimate(x, z),
}
}
}
});