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
use crate::{DependentJoint, Distribution, IndependentJoint, RandomVariable};
use rand::prelude::*;
use std::{
fmt::Debug,
marker::PhantomData,
ops::{BitAnd, Mul},
};
#[derive(Clone, Debug)]
pub struct TransformedDistribution<D, T, U, V>
where
D: Distribution<Value = T, Condition = U>,
T: RandomVariable,
U: Clone + Debug + Send + Sync,
V: RandomVariable,
{
distribution: D,
phantom: PhantomData<V>,
}
impl<D, T, U, V> TransformedDistribution<D, T, U, V>
where
D: Distribution<Value = T, Condition = U>,
T: RandomVariable,
U: Clone + Debug + Send + Sync,
V: RandomVariable,
{
pub fn new(distribution: D) -> Self {
Self {
distribution,
phantom: PhantomData,
}
}
}
impl<D, T, U, V> Distribution for TransformedDistribution<D, T, U, V>
where
D: Distribution<Value = T, Condition = U>,
T: RandomVariable,
U: RandomVariable,
V: RandomVariable,
{
type Value = (T, V);
type Condition = (U, V);
fn fk(
&self,
x: &Self::Value,
theta: &Self::Condition,
) -> Result<f64, crate::DistributionError> {
self.distribution.fk(&x.0, &theta.0)
}
fn sample(
&self,
theta: &Self::Condition,
rng: &mut dyn RngCore,
) -> Result<Self::Value, crate::DistributionError> {
Ok((self.distribution.sample(&theta.0, rng)?, theta.1.clone()))
}
}
pub trait TransformableDistribution: Distribution + Sized {
fn transform<V>(self) -> TransformedDistribution<Self, Self::Value, Self::Condition, V>
where
V: RandomVariable;
}
impl<D, T, U1> TransformableDistribution for D
where
D: Distribution<Value = T, Condition = U1>,
T: RandomVariable,
U1: RandomVariable,
{
fn transform<V>(self) -> TransformedDistribution<Self, Self::Value, Self::Condition, V>
where
V: RandomVariable,
{
TransformedDistribution::<Self, Self::Value, Self::Condition, V>::new(self)
}
}
impl<D, T, U, V, Rhs, TRhs> Mul<Rhs> for TransformedDistribution<D, T, U, V>
where
D: Distribution<Value = T, Condition = U>,
T: RandomVariable,
U: RandomVariable,
V: RandomVariable,
Rhs: Distribution<Value = TRhs, Condition = (U, V)>,
TRhs: RandomVariable,
{
type Output = IndependentJoint<Self, Rhs, (T, V), TRhs, (U, V)>;
fn mul(self, rhs: Rhs) -> Self::Output {
IndependentJoint::new(self, rhs)
}
}
impl<D, T, U, V, Rhs, URhs> BitAnd<Rhs> for TransformedDistribution<D, T, U, V>
where
D: Distribution<Value = T, Condition = U>,
T: RandomVariable,
U: RandomVariable,
V: RandomVariable,
Rhs: Distribution<Value = (U, V), Condition = URhs>,
URhs: RandomVariable,
{
type Output = DependentJoint<Self, Rhs, (T, V), (U, V), URhs>;
fn bitand(self, rhs: Rhs) -> Self::Output {
DependentJoint::new(self, rhs)
}
}