causal-hub 0.0.5

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
mod bayesian_network;
use std::ops::{DivAssign, MulAssign};

use approx::{AbsDiffEq, RelativeEq};
pub use bayesian_network::*;

mod continuous_time_bayesian_network;
pub use continuous_time_bayesian_network::*;
use itertools::Either;
use rand::Rng;

mod graphs;
use std::fmt::Debug;

pub use graphs::*;

use crate::types::{Error, Labels, Result, Set};

/// A trait for models with labelled variables.
pub trait Labelled {
    /// Returns the labels of the variables.
    ///
    /// # Returns
    ///
    /// A reference to the labels.
    ///
    fn labels(&self) -> &Labels;

    /// Return the variable index for a given label.
    ///
    /// # Arguments
    ///
    /// * `x` - The label of the variable.
    ///
    /// # Errors
    ///
    /// * If the label is not found.
    ///
    /// # Returns
    ///
    /// The index of the variable.
    ///
    #[inline]
    fn label_to_index(&self, x: &str) -> Result<usize> {
        self.labels()
            .get_index_of(x)
            .ok_or_else(|| Error::MissingLabel(x))
    }

    /// Return the label for a given variable index.
    ///
    /// # Arguments
    ///
    /// * `x` - The index of the variable.
    ///
    /// # Errors
    ///
    /// * If the index is out of bounds.
    ///
    /// # Returns
    ///
    /// The label of the variable.
    ///
    #[inline]
    fn index_to_label(&self, x: usize) -> Result<&str> {
        self.labels()
            .get_index(x)
            .map(|x| x.as_str())
            .ok_or_else(|| Error::IndexOutOfBounds(x))
    }

    /// Maps an index from this model to another model with the same label.
    ///
    /// # Arguments
    ///
    /// * `x` - The index in this model.
    /// * `other` - The labels of the other model.
    ///
    /// # Errors
    ///
    /// * If the index is out of bounds.
    /// * If the label does not exist in the other model.
    ///
    /// # Returns
    ///
    /// The index in the other model.
    ///
    #[inline]
    fn index_to(&self, x: usize, other: &Labels) -> Result<usize> {
        // Get the label of the variable in this model.
        let label = self.index_to_label(x)?;
        // Get the index of the variable in the other model.
        other
            .get_index_of(label)
            .ok_or_else(|| Error::MissingLabel(label))
    }

    /// Maps a set of indices from this model to another model with the same labels.
    ///
    /// # Arguments
    ///
    /// * `x` - The set of indices in this model.
    /// * `other` - The labels of the other model.
    ///
    /// # Errors
    ///
    /// * If any index is out of bounds.
    /// * If any label does not exist in the other model.
    ///
    /// # Returns
    ///
    /// The set of indices in the other model.
    ///
    #[inline]
    fn indices_to(&self, x: &Set<usize>, other: &Labels) -> Result<Set<usize>> {
        x.iter().map(|&x| self.index_to(x, other)).collect()
    }

    /// Maps an index from another model to this model with the same label.
    ///
    /// # Arguments
    ///
    /// * `x` - The index in the other model.
    /// * `other` - The labels of the other model.
    ///
    /// # Errors
    ///
    /// * If the index is out of bounds.
    /// * If the label does not exist in this model.
    ///
    /// # Returns
    ///
    /// The index in this model.
    ///
    #[inline]
    fn index_from(&self, x: usize, other: &Labels) -> Result<usize> {
        // Get the label of the variable in the other model.
        let label = other
            .get_index(x)
            .ok_or_else(|| Error::IndexOutOfBounds(x))?;
        // Get the index of the variable in this model.
        self.labels()
            .get_index_of(label)
            .ok_or_else(|| Error::MissingLabel(label))
    }

    /// Maps a set of indices from another model to this model with the same labels.
    ///
    /// # Arguments
    ///
    /// * `x` - The set of indices in the other model.
    /// * `other` - The labels of the other model.
    ///
    /// # Errors
    ///
    /// * If any index is out of bounds.
    /// * If any label does not exist in this model.
    ///
    /// # Returns
    ///
    /// The set of indices in this model.
    ///
    #[inline]
    fn indices_from(&self, x: &Set<usize>, other: &Labels) -> Result<Set<usize>> {
        x.iter().map(|&x| self.index_from(x, other)).collect()
    }
}

impl<L, R> Labelled for Either<L, R>
where
    L: Labelled,
    R: Labelled,
{
    fn labels(&self) -> &Labels {
        match self {
            Either::Left(l) => l.labels(),
            Either::Right(r) => r.labels(),
        }
    }
}

/// A trait for conditional probability distributions.
pub trait CPD: Clone + Debug + Labelled + PartialEq + AbsDiffEq + RelativeEq {
    /// The type of the support.
    type Support;
    /// The type of the parameters.
    type Parameters;
    /// The type of the sufficient statistics.
    type Statistics;

    /// Returns the labels of the conditioned variables.
    ///
    /// # Returns
    ///
    /// A reference to the conditioning labels.
    ///
    fn conditioning_labels(&self) -> &Labels;

    /// Returns the parameters.
    ///
    /// # Returns
    ///
    /// A reference to the parameters.
    ///
    fn parameters(&self) -> &Self::Parameters;

    /// Returns the parameters size.
    ///
    /// # Returns
    ///
    /// The parameters size.
    ///
    fn parameters_size(&self) -> usize;

    /// Returns the sufficient statistics, if any.
    ///
    /// # Returns
    ///
    /// An option containing a reference to the sufficient statistics.
    ///
    fn fitted_statistics(&self) -> Option<&Self::Statistics>;

    /// Returns the log-likelihood of the fitted dataset, if any.
    ///
    /// # Returns
    ///
    /// An option containing the log-likelihood.
    ///
    fn fitted_log_likelihood(&self) -> Option<f64>;

    /// Returns the value of probability (mass or density) function for P(X = x | Z = z).
    ///
    /// # Arguments
    ///
    /// * `x` - The value of the conditioned variables.
    /// * `z` - The value of the conditioning variables.
    ///
    /// # Errors
    ///
    /// * If the value of the conditioned variables is out of bounds.
    /// * If the value of the conditioning variables is out of bounds.
    ///
    /// # Returns
    ///
    /// The probability P(X = x | Z = z).
    ///
    fn pf(&self, x: &Self::Support, z: &Self::Support) -> Result<f64>;

    /// Samples from the conditional distribution P(X | Z = z).
    ///
    /// # Arguments
    ///
    /// * `rng` - A mutable reference to a random number generator.
    /// * `z` - The value of the conditioning variables.
    ///
    /// # Errors
    ///
    /// * If the value of the conditioning variables is out of bounds.
    ///
    /// # Returns
    ///
    /// A sample from P(X | Z = z).
    ///
    fn sample<R: Rng>(&self, rng: &mut R, z: &Self::Support) -> Result<Self::Support>;
}

/// A trait for conditional intensity matrices.
pub trait CIM: Clone + Debug + Labelled + PartialEq + AbsDiffEq + RelativeEq {
    /// The type of the support.
    type Support;
    /// The type of the parameters.
    type Parameters;
    /// The type of the sufficient statistics.
    type Statistics;

    /// Returns the labels of the conditioned variables.
    ///
    /// # Returns
    ///
    /// A reference to the conditioning labels.
    ///
    fn conditioning_labels(&self) -> &Labels;

    /// Returns the parameters.
    ///
    /// # Returns
    ///
    /// A reference to the parameters.
    ///
    fn parameters(&self) -> &Self::Parameters;

    /// Returns the parameters size.
    ///
    /// # Returns
    ///
    /// The parameters size.
    ///
    fn parameters_size(&self) -> usize;

    /// Returns the sufficient statistics, if any.
    ///
    /// # Returns
    ///
    /// An option containing a reference to the sufficient statistics.
    ///
    fn fitted_statistics(&self) -> Option<&Self::Statistics>;

    /// Returns the log-likelihood of the fitted dataset, if any.
    ///
    /// # Returns
    ///
    /// An option containing the log-likelihood.
    ///
    fn fitted_log_likelihood(&self) -> Option<f64>;
}

/// A trait for potential functions.
pub trait Phi:
    Clone
    + Debug
    + Labelled
    + PartialEq
    + AbsDiffEq
    + RelativeEq
    + for<'a> MulAssign<&'a Self>
    + for<'a> DivAssign<&'a Self>
{
    /// The type of the CPD.
    type CPD;
    /// The type of the parameters.
    type Parameters;
    /// The type of the evidence.
    type Evidence;

    /// Returns the parameters.
    ///
    /// # Returns
    ///
    /// A reference to the parameters.
    ///
    fn parameters(&self) -> &Self::Parameters;

    /// Returns the parameters size.
    ///
    /// # Returns
    ///
    /// The parameters size.
    ///
    fn parameters_size(&self) -> usize;

    /// Conditions the potential on a set of variables.
    ///
    /// # Arguments
    ///
    /// * `e` - A map from variable indices to their observed states.
    ///
    /// # Returns
    ///
    /// A new potential instance.
    ///
    fn condition(&self, e: &Self::Evidence) -> Result<Self>;

    /// Marginalizes the potential over a set of variables.
    ///
    /// # Arguments
    ///
    /// * `x` - A set of variable indices to marginalize over.
    ///
    /// # Returns
    ///
    /// A new potential instance.
    ///
    fn marginalize(&self, x: &Set<usize>) -> Result<Self>;

    /// Normalizes the potential.
    ///
    /// # Returns
    ///
    /// The normalized potential.
    ///
    fn normalize(&self) -> Result<Self>;

    /// Converts a CPD P(X | Z) to a potential \phi(X \cup Z).
    ///
    /// # Arguments
    ///
    /// * `cpd` - The CPD to convert.
    ///
    /// # Returns
    ///
    /// The corresponding potential.
    ///
    fn from_cpd(cpd: Self::CPD) -> Result<Self>;

    /// Converts a potential \phi(X \cup Z) to a CPD P(X | Z).
    ///
    /// # Arguments
    ///
    /// * `x` - The set of variables.
    /// * `z` - The set of conditioning variables.
    ///
    /// # Returns
    ///
    /// The corresponding CPD.
    ///
    fn into_cpd(self, x: &Set<usize>, z: &Set<usize>) -> Result<Self::CPD>;
}