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
use std::{
fmt::Debug,
hash::{Hash, Hasher},
ops::{Div, Mul},
};
use backtrace::Backtrace as trc;
use derive_more::*;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::prelude::*;
#[derive(
PartialOrd,
Clone,
Copy,
Default,
Debug,
Display,
Into,
AsRef,
AsMut,
Add,
Sub,
Mul,
Div,
Rem,
Sum,
AddAssign,
SubAssign,
MulAssign,
DivAssign,
RemAssign,
Serialize,
Deserialize,
)]
pub struct Entropy(f64);
impl Hash for Entropy {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
impl PartialEq for Entropy {
fn eq(&self, other: &Self) -> bool {
self.0.to_bits() == other.0.to_bits()
}
}
impl From<f64> for Entropy {
fn from(entropy: f64) -> Self {
debug_assert!(entropy >= 0.);
Self(entropy)
}
}
impl Entropy {
pub fn new(entropy: f64) -> Self {
debug_assert!(entropy >= 0.);
Self(entropy)
}
}
#[derive(
PartialOrd,
Clone,
Copy,
Default,
Debug,
Display,
Into,
AsRef,
AsMut,
Add,
Sub,
Mul,
Div,
Rem,
Sum,
AddAssign,
SubAssign,
MulAssign,
DivAssign,
RemAssign,
Serialize,
Deserialize,
)]
pub struct Probability(f64);
impl Hash for Probability {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.to_bits().hash(state);
}
}
impl PartialEq for Probability {
fn eq(&self, other: &Self) -> bool {
self.0.to_bits() == other.0.to_bits()
}
}
impl From<f64> for Probability {
fn from(probability: f64) -> Self {
debug_assert!((0. ..=1.).contains(&probability));
Self(probability)
}
}
impl Mul<Probability> for Probability {
type Output = Probability;
fn mul(self, rhs: Probability) -> Self::Output {
Self(self.0 * rhs.0)
}
}
impl Div<Probability> for Probability {
type Output = Probability;
fn div(self, rhs: Probability) -> Self::Output {
Self(self.0 / rhs.0)
}
}
impl Probability {
pub fn new(probability: f64) -> Self {
debug_assert!((0. ..=1.).contains(&probability));
Self(probability)
}
pub fn from_probability_weight(probability_weight: ProbabilityWeight) -> Self {
Self(probability_weight.into())
}
pub fn to_f64(self) -> f64 {
self.0
}
pub fn check_in_bound(&self) {
assert!((0. ..=1.).contains(&self.0));
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Error)]
pub enum UnitsError {
#[error("Probability is out of range: {probability:#?}")]
ProbabilityOutOfRange {
probability: Probability,
context: trc,
},
#[error("Probability sum is not 1 but {probability_sum:#?}")]
ProbabilitySumNot1 {
probability_sum: Probability,
context: trc,
},
}