causal-hub 0.0.6

A library for causal models, inference and discovery.
Documentation
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
use core::f64;
use std::cell::RefCell;

use ndarray::prelude::*;
use ndarray_stats::QuantileExt;
use rand::{
    Rng, RngExt, SeedableRng,
    distr::{Distribution, weighted::WeightedIndex},
};
use rand_distr::Exp;
use rayon::prelude::*;

use crate::{
    datasets::{CatSample, CatTable, CatTrj, CatType, GaussTable},
    models::{
        BN, CIM, CPD, CTBN, CatBN, CatCTBN, GaussBN, HasLabels, MixedBN, MixedCPD, MixedSample,
        MixedSupport, MixedTable,
    },
    samplers::{BNSampler, CTBNSampler, ParBNSampler, ParCTBNSampler},
    set,
    types::{EPSILON, Error, Map, Result, Set},
};

/// A forward sampler.
#[derive(Debug)]
pub struct ForwardSampler<'a, R, M> {
    rng: RefCell<&'a mut R>,
    model: &'a M,
}

impl<'a, R, M> ForwardSampler<'a, R, M> {
    /// Construct a new forward sampler.
    ///
    /// # Arguments
    ///
    /// * `rng` - A random number generator.
    /// * `model` - A reference to the model to sample from.
    ///
    /// # Returns
    ///
    /// A new `ForwardSampler` instance.
    ///
    #[inline]
    pub fn new(rng: &'a mut R, model: &'a M) -> Result<Self> {
        // Wrap the RNG in a RefCell to allow interior mutability.
        let rng = RefCell::new(rng);

        Ok(Self { rng, model })
    }
}

impl<R: Rng> BNSampler<CatBN> for ForwardSampler<'_, R, CatBN> {
    type Sample = <CatBN as BN>::Sample;
    type Samples = <CatBN as BN>::Samples;

    fn sample(&self) -> Result<Self::Sample> {
        // Get a mutable reference to the RNG.
        let mut rng = self.rng.borrow_mut();
        // Allocate the sample.
        let mut sample = Array::zeros(self.model.labels().len());

        // For each vertex in the topological order ...
        for &i in self.model.topological_order() {
            // Get the CPD.
            let cpd_i = &self.model.cpds()[i];
            // Compute the index on the parents to condition on.
            let pa_i = self.model.graph().parents(&set![i])?;
            let pa_i = pa_i.iter().map(|&z| sample[z]).collect();
            // Sample from the distribution.
            sample[i] = cpd_i.sample(&mut rng, &pa_i)?[0];
        }

        Ok(sample)
    }

    fn sample_n(&self, n: usize) -> Result<Self::Samples> {
        // Allocate the dataset.
        let mut dataset = Array::zeros((n, self.model.labels().len()));

        // For each sample, sample from the distribution using iterators.
        dataset
            .rows_mut()
            .into_iter()
            .try_for_each(|mut row| -> Result<_> {
                // Sample from the distribution.
                row.assign(&self.sample()?);

                Ok(())
            })?;

        // Construct the dataset.
        CatTable::new(self.model.support().clone(), dataset)
    }
}

impl<R: Rng + SeedableRng> ParBNSampler<CatBN> for ForwardSampler<'_, R, CatBN> {
    type Samples = <CatBN as BN>::Samples;

    fn par_sample_n(&self, n: usize) -> Result<Self::Samples> {
        // Get a mutable reference to the RNG.
        let rng = self.rng.borrow_mut();
        // Generate a random seed for each sample.
        let seeds: Vec<_> = rng.random_iter().take(n).collect();

        // Allocate the samples.
        let mut samples = Array::zeros((n, self.model.labels().len()));

        // Sample the samples in parallel.
        seeds
            .into_par_iter()
            .zip(samples.axis_iter_mut(Axis(0)))
            .try_for_each(|(seed, mut row)| -> Result<()> {
                // Create a new random number generator with the seed.
                let mut rng = R::seed_from_u64(seed);
                // Create a new sampler with the random number generator and model.
                let sampler = ForwardSampler::new(&mut rng, self.model)?;
                // Sample from the distribution.
                row.assign(&sampler.sample()?);

                Ok(())
            })?;

        // Construct the dataset.
        CatTable::new(self.model.support().clone(), samples)
    }
}

impl<R: Rng> BNSampler<GaussBN> for ForwardSampler<'_, R, GaussBN> {
    type Sample = <GaussBN as BN>::Sample;
    type Samples = <GaussBN as BN>::Samples;

    fn sample(&self) -> Result<Self::Sample> {
        // Get a mutable reference to the RNG.
        let mut rng = self.rng.borrow_mut();
        // Allocate the sample.
        let mut sample = Array::zeros(self.model.labels().len());

        // For each vertex in the topological order ...
        for &i in self.model.topological_order() {
            // Get the CPD.
            let cpd_i = &self.model.cpds()[i];
            // Get the parents.
            let pa_i = self.model.graph().parents(&set![i])?;
            let pa_i = pa_i.iter().map(|&z| sample[z]).collect();
            // Compute the value of the variable.
            sample[i] = cpd_i.sample(&mut rng, &pa_i)?[0];
        }

        Ok(sample)
    }

    fn sample_n(&self, n: usize) -> Result<Self::Samples> {
        // Allocate the samples.
        let mut samples = Array::zeros((n, self.model.labels().len()));

        // For each sample, sample from the distribution using iterators.
        samples
            .rows_mut()
            .into_iter()
            .try_for_each(|mut row| -> Result<_> {
                // Sample from the distribution.
                row.assign(&self.sample()?);

                Ok(())
            })?;

        // Construct the dataset.
        GaussTable::new(self.model.labels().clone(), samples)
    }
}

impl<R: Rng + SeedableRng> ParBNSampler<GaussBN> for ForwardSampler<'_, R, GaussBN> {
    type Samples = <GaussBN as BN>::Samples;

    fn par_sample_n(&self, n: usize) -> Result<Self::Samples> {
        // Get a mutable reference to the RNG.
        let rng = self.rng.borrow_mut();
        // Generate a random seed for each sample.
        let seeds: Vec<_> = rng.random_iter().take(n).collect();

        // Allocate the samples.
        let mut samples = Array::zeros((n, self.model.labels().len()));

        // Sample the samples in parallel.
        seeds
            .into_par_iter()
            .zip(samples.axis_iter_mut(Axis(0)))
            .try_for_each(|(seed, mut row)| -> Result<()> {
                // Create a new random number generator with the seed.
                let mut rng = R::seed_from_u64(seed);
                // Create a new sampler with the random number generator and model.
                let sampler = ForwardSampler::new(&mut rng, self.model)?;
                // Sample from the distribution.
                row.assign(&sampler.sample()?);
                Ok(())
            })?;

        // Construct the dataset.
        GaussTable::new(self.model.labels().clone(), samples)
    }
}

// ── MixedBN sampler helpers & macro ──────────────────────────────────

macro_rules! mixed_pure_dispatch {
    ($self:expr, $cat:block, $gauss:block) => {{
        let ok = $self
            .model
            .cpds()
            .values()
            .all(|distribution| matches!(distribution, MixedCPD::Categorical(_)));
        if ok {
            $cat
        } else {
            let ok = $self
                .model
                .cpds()
                .values()
                .all(|distribution| matches!(distribution, MixedCPD::Gaussian(_)));
            if ok {
                $gauss
            } else {
                return Err(Error::InvalidParameter(
                    "model",
                    "mixed CPD types not yet supported for forward sampling",
                ));
            }
        }
    }};
}

fn extract_cat_support(
    support: &crate::types::Map<String, MixedSupport>,
) -> Map<String, Set<String>> {
    support
        .iter()
        .map(|(label, mixed_supp)| match mixed_supp {
            MixedSupport::Categorical(cpd_support) => {
                let states = cpd_support[label].clone();
                (label.clone(), states)
            }
            _ => unreachable!(), // A mixed-BN's support is always categorical.
        })
        .collect()
}

// ── MixedBN sampler ──────────────────────────────────────────────────

impl<R: Rng> BNSampler<MixedBN> for ForwardSampler<'_, R, MixedBN> {
    type Sample = MixedSample;
    type Samples = MixedTable;

    fn sample(&self) -> Result<Self::Sample> {
        let mut rng = self.rng.borrow_mut();
        let n_vars = self.model.labels().len();

        mixed_pure_dispatch!(
            self,
            {
                let mut sample = Array1::<CatType>::zeros(n_vars);
                for &i in self.model.topological_order() {
                    let cpd_i = &self.model.cpds()[i];
                    let pa_i = self.model.graph().parents(&set![i])?;
                    let pa_vals: Array1<CatType> = pa_i.iter().map(|&z| sample[z]).collect();
                    let pa_sample = MixedSample::Categorical(pa_vals);
                    let result = cpd_i.sample(&mut rng, &pa_sample)?;
                    if let MixedSample::Categorical(v) = result {
                        sample[i] = v[0];
                    }
                }
                Ok(MixedSample::Categorical(sample))
            },
            {
                let mut sample = Array1::<f64>::zeros(n_vars);
                for &i in self.model.topological_order() {
                    let cpd_i = &self.model.cpds()[i];
                    let pa_i = self.model.graph().parents(&set![i])?;
                    let pa_vals: Array1<f64> = pa_i.iter().map(|&z| sample[z]).collect();
                    let pa_sample = MixedSample::Gaussian(pa_vals);
                    let result = cpd_i.sample(&mut rng, &pa_sample)?;
                    if let MixedSample::Gaussian(v) = result {
                        sample[i] = v[0];
                    }
                }
                Ok(MixedSample::Gaussian(sample))
            }
        )
    }

    fn sample_n(&self, n: usize) -> Result<Self::Samples> {
        mixed_pure_dispatch!(
            self,
            {
                let mut dataset = Array::zeros((n, self.model.labels().len()));
                dataset
                    .rows_mut()
                    .into_iter()
                    .try_for_each(|mut row| -> Result<_> {
                        if let MixedSample::Categorical(stats) = self.sample()? {
                            row.assign(&stats);
                        }
                        Ok(())
                    })?;
                let cat_support = extract_cat_support(&self.model.support());
                CatTable::new(cat_support, dataset).map(MixedTable::Categorical)
            },
            {
                let mut dataset = Array::zeros((n, self.model.labels().len()));
                dataset
                    .rows_mut()
                    .into_iter()
                    .try_for_each(|mut row| -> Result<_> {
                        if let MixedSample::Gaussian(stats) = self.sample()? {
                            row.assign(&stats);
                        }
                        Ok(())
                    })?;
                GaussTable::new(self.model.labels().clone(), dataset).map(MixedTable::Gaussian)
            }
        )
    }
}

impl<R: Rng + SeedableRng> ParBNSampler<MixedBN> for ForwardSampler<'_, R, MixedBN> {
    type Samples = MixedTable;

    fn par_sample_n(&self, n: usize) -> Result<Self::Samples> {
        let rng = self.rng.borrow_mut();
        let seeds: Vec<_> = rng.random_iter().take(n).collect();

        mixed_pure_dispatch!(
            self,
            {
                let mut samples = Array::zeros((n, self.model.labels().len()));
                seeds
                    .into_par_iter()
                    .zip(samples.axis_iter_mut(Axis(0)))
                    .try_for_each(|(seed, mut row)| -> Result<()> {
                        let mut rng = R::seed_from_u64(seed);
                        let sampler = ForwardSampler::new(&mut rng, self.model)?;
                        if let MixedSample::Categorical(stats) = sampler.sample()? {
                            row.assign(&stats);
                        }
                        Ok(())
                    })?;
                let cat_support = extract_cat_support(&self.model.support());
                CatTable::new(cat_support, samples).map(MixedTable::Categorical)
            },
            {
                let mut samples = Array::zeros((n, self.model.labels().len()));
                seeds
                    .into_par_iter()
                    .zip(samples.axis_iter_mut(Axis(0)))
                    .try_for_each(|(seed, mut row)| -> Result<()> {
                        let mut rng = R::seed_from_u64(seed);
                        let sampler = ForwardSampler::new(&mut rng, self.model)?;
                        if let MixedSample::Gaussian(stats) = sampler.sample()? {
                            row.assign(&stats);
                        }
                        Ok(())
                    })?;
                GaussTable::new(self.model.labels().clone(), samples).map(MixedTable::Gaussian)
            }
        )
    }
}

impl<R: Rng> ForwardSampler<'_, R, CatCTBN> {
    /// Sample transition time for variable `X_i` with state `x_i`.
    fn sample_time(&self, event: &CatSample, i: usize) -> Result<f64> {
        // Cast the state to usize.
        let x = event[i] as usize;
        // Get the CIM.
        let cim_i = &self.model.cims()[i];
        // Compute the index on the parents to condition on.
        let pa_i = self.model.graph().parents(&set![i])?;
        let pa_i = pa_i.iter().map(|&z| event[z] as usize);
        let pa_i = cim_i.conditioning_multi_index().ravel(pa_i);
        // Get the distribution of the vertex.
        let q_i_x = -cim_i.parameters()[[pa_i, x, x]];
        // Initialize the exponential distribution.
        let exp_i_x = Exp::new(q_i_x)
            .map_err(|evidence| Error::RandDistr(&format!("Invalid lambda: {}", evidence)))?;
        // Sample the transition time.
        Ok(exp_i_x.sample(&mut self.rng.borrow_mut()))
    }
}

impl<R: Rng> CTBNSampler<CatCTBN> for ForwardSampler<'_, R, CatCTBN> {
    type Sample = <CatCTBN as CTBN>::Trajectory;
    type Samples = <CatCTBN as CTBN>::Trajectories;

    #[inline]
    fn sample_by_length(&self, max_length: usize) -> Result<Self::Sample> {
        // Delegate to generic function.
        self.sample_by_length_or_time(max_length, f64::MAX)
    }

    #[inline]
    fn sample_by_time(&self, max_time: f64) -> Result<Self::Sample> {
        // Delegate to generic function.
        self.sample_by_length_or_time(usize::MAX, max_time)
    }

    fn sample_by_length_or_time(&self, max_length: usize, max_time: f64) -> Result<Self::Sample> {
        // Check length is positive.
        if max_length == 0 {
            return Err(Error::InvalidParameter(
                "max_length",
                "The maximum length of the trajectory must be strictly positive.",
            ));
        }
        // Check time is positive.
        if max_time <= 0. {
            return Err(Error::InvalidParameter("max_time", "must be positive"));
        }

        // Allocate the trajectory components.
        let mut sample_events = Vec::new();
        let mut sample_times = Vec::new();

        // Sample the initial support.
        let mut event = {
            let mut rng = self.rng.borrow_mut();
            let initial = self.model.initial_distribution();
            let initial = ForwardSampler::new(&mut rng, initial)?;
            initial.sample()?
        };
        // Append the initial state to the trajectory.
        sample_events.push(event.clone());
        sample_times.push(0.);

        // Sample the transition time.
        let mut times: Array1<_> = (0..event.len())
            .map(|i| self.sample_time(&event, i))
            .collect::<Result<_>>()?;

        // Get the variable that transitions first.
        let mut i = times
            .argmin()
            .map_err(|evidence| Error::Stats(&format!("Failed to find min time: {}", evidence)))?;
        // Set global time.
        let mut time = times[i];

        // While:
        //  1. the length of the trajectory is less than max_length, and ...
        //  2. the time is less than max_time ...
        while sample_events.len() < max_length && time < max_time {
            // Cast the state to usize.
            let x = event[i] as usize;
            // Get the CIM.
            let cim_i = &self.model.cims()[i];
            // Compute the index on the parents to condition on.
            let pa_i = self.model.graph().parents(&set![i])?;
            let pa_i = pa_i.iter().map(|&z| event[z] as usize);
            let pa_i = cim_i.conditioning_multi_index().ravel(pa_i);
            // Get the distribution of the vertex.
            let mut q_i_zx = cim_i.parameters().slice(s![pa_i, x, ..]).to_owned();
            // Set the diagonal element to zero.
            q_i_zx[x] = 0.;
            // Normalize the probabilities.
            q_i_zx /= q_i_zx.sum();
            // Initialize a weighted index sampler.
            let s_i_zx = WeightedIndex::new(&q_i_zx).map_err(|evidence| {
                Error::RandDistr(&format!("Invalid probabilities: {}", evidence))
            })?;
            // Sample the next event.
            event[i] = s_i_zx.sample(&mut self.rng.borrow_mut()) as CatType;
            // Append the event to the trajectory.
            sample_events.push(event.clone());
            sample_times.push(time);
            // Update the transition times for { X } U Ch(X).
            for j in std::iter::once(i).chain(self.model.graph().children(&set![i])?) {
                // Sample the transition time.
                times[j] = time + self.sample_time(&event, j)?;
            }
            // Add a small epsilon to avoid zero transition times.
            times += EPSILON;
            // Get the variable to transition first.
            i = times.argmin().map_err(|evidence| {
                Error::Stats(&format!("Failed to find min time: {}", evidence))
            })?;
            // Update the global time.
            time = times[i];
        }

        // Get the support of the CIMs.
        let support = self.model.support().clone();

        // Convert the events to a 2D array.
        let shape = (sample_events.len(), sample_events[0].len());
        let sample_events = Array::from_iter(sample_events.into_iter().flatten())
            .into_shape_with_order(shape)
            .map_err(|evidence| Error::Shape(&evidence.to_string()))?;
        // Convert the times to a 1D array.
        let sample_times = Array::from_iter(sample_times);

        // Return the trajectory.
        CatTrj::new(support, sample_events, sample_times)
    }

    #[inline]
    fn sample_n_by_length(&self, max_length: usize, n: usize) -> Result<Self::Samples> {
        (0..n).map(|_| self.sample_by_length(max_length)).collect()
    }

    #[inline]
    fn sample_n_by_time(&self, max_time: f64, n: usize) -> Result<Self::Samples> {
        (0..n).map(|_| self.sample_by_time(max_time)).collect()
    }

    #[inline]
    fn sample_n_by_length_or_time(
        &self,
        max_length: usize,
        max_time: f64,
        n: usize,
    ) -> Result<Self::Samples> {
        (0..n)
            .map(|_| self.sample_by_length_or_time(max_length, max_time))
            .collect()
    }
}

impl<R: Rng + SeedableRng> ParCTBNSampler<CatCTBN> for ForwardSampler<'_, R, CatCTBN> {
    type Samples = <CatCTBN as CTBN>::Trajectories;

    #[inline]
    fn par_sample_n_by_length(&self, max_length: usize, n: usize) -> Result<Self::Samples> {
        self.par_sample_n_by_length_or_time(max_length, f64::MAX, n)
    }

    #[inline]
    fn par_sample_n_by_time(&self, max_time: f64, n: usize) -> Result<Self::Samples> {
        self.par_sample_n_by_length_or_time(usize::MAX, max_time, n)
    }

    fn par_sample_n_by_length_or_time(
        &self,
        max_length: usize,
        max_time: f64,
        n: usize,
    ) -> Result<Self::Samples> {
        // Get a mutable reference to the RNG.
        let rng = self.rng.borrow_mut();
        // Generate a random seed for each trajectory.
        let seeds: Vec<_> = rng.random_iter().take(n).collect();
        // Sample the trajectories in parallel.
        seeds
            .into_par_iter()
            .map(|seed| {
                // Create a new random number generator with the seed.
                let mut rng = R::seed_from_u64(seed);
                // Create a new sampler with the random number generator and model.
                let sampler = ForwardSampler::new(&mut rng, self.model)?;
                // Sample the trajectory.
                sampler.sample_by_length_or_time(max_length, max_time)
            })
            .collect()
    }
}