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
pub mod cdf;
use std::mem;
use std::f64;
use std::iter;
use std::ops::{Add, Sub, Mul, Div};
use itertools::linspace;
use itertools::Itertools;
use itertools::misc::ToFloat;
const LOG_TO_PHRED_FACTOR: f64 = -4.3429448190325175;
const PHRED_TO_LOG_FACTOR: f64 = -0.23025850929940456;
fn ln_1m_exp(p: f64) -> f64 {
assert!(p <= 0.0);
if p < -0.693 {
(-p.exp()).ln_1p()
} else {
(-p.exp_m1()).ln()
}
}
custom_derive! {
#[derive(
NewtypeFrom,
NewtypeDeref,
NewtypeAdd(*),
NewtypeSub(*),
NewtypeMul(*),
NewtypeDiv(*),
PartialEq,
PartialOrd,
Copy,
Clone,
Debug,
Default,
RustcDecodable,
RustcEncodable
)]
#[cfg_attr(feature = "serde_macros", derive(Serialize, Deserialize))]
pub struct Prob(pub f64);
}
impl Prob {
pub fn checked(p: f64) -> Result<Self, ProbError> {
if p >= 0.0 && p <= 1.0 {
Ok(Prob(p))
} else {
Err(ProbError::InvalidProb(p))
}
}
}
custom_derive! {
#[derive(
NewtypeFrom,
NewtypeDeref,
NewtypeAdd(*),
NewtypeSub(*),
PartialEq,
PartialOrd,
Copy,
Clone,
Debug,
RustcDecodable,
RustcEncodable
)]
#[cfg_attr(feature = "serde_macros", derive(Serialize, Deserialize))]
pub struct LogProb(pub f64);
}
custom_derive! {
#[derive(
NewtypeFrom,
NewtypeDeref,
NewtypeAdd(*),
NewtypeSub(*),
PartialEq,
PartialOrd,
Copy,
Clone,
Debug,
RustcDecodable,
RustcEncodable
)]
#[cfg_attr(feature = "serde_macros", derive(Serialize, Deserialize))]
pub struct PHREDProb(pub f64);
}
pub type ScanIter<I> = iter::Scan<<I as IntoIterator>::IntoIter, LogProb, fn(&mut LogProb, LogProb) -> Option<LogProb>>;
static LOGPROB_LN_ZERO: LogProb = LogProb(f64::NEG_INFINITY);
static LOGPROB_LN_ONE: LogProb = LogProb(0.0);
impl LogProb {
pub fn ln_zero() -> LogProb {
LOGPROB_LN_ZERO
}
pub fn ln_one() -> LogProb {
LOGPROB_LN_ONE
}
pub fn ln_one_minus_exp(&self) -> LogProb {
LogProb(ln_1m_exp(**self))
}
pub fn ln_sum_exp(probs: &[LogProb]) -> LogProb {
if probs.is_empty() {
Self::ln_zero()
} else {
let mut pmax = probs[0];
let mut imax = 0;
for (i, &p) in probs.iter().enumerate().skip(1) {
if p > pmax {
pmax = p;
imax = i;
}
}
if pmax == Self::ln_zero() {
Self::ln_zero()
} else if *pmax == f64::INFINITY {
LogProb(f64::INFINITY)
} else {
pmax + LogProb(
(probs.iter()
.enumerate()
.filter_map(|(i, p)| {
if i == imax {
None
} else {
Some((p - pmax).exp())
}
})
.fold(0.0, |s, e| s + e)
).ln_1p()
)
}
}
}
pub fn ln_add_exp(self, other: LogProb) -> LogProb {
let (mut p0, mut p1) = (self, other);
if p1 > p0 {
mem::swap(&mut p0, &mut p1);
}
if p0 == Self::ln_zero() {
Self::ln_zero()
} else if *p0 == f64::INFINITY {
LogProb(f64::INFINITY)
} else {
p0 + LogProb((p1 - p0).exp().ln_1p())
}
}
pub fn ln_sub_exp(self, other: LogProb) -> LogProb {
let (p0, p1) = (self, other);
assert!(p0 >= p1,
"Subtraction would lead to negative probability, which is undefined in log space.");
if relative_eq!(*p0, *p1) || p0 == Self::ln_zero() {
Self::ln_zero()
} else if *p0 == f64::INFINITY {
LogProb(f64::INFINITY)
} else {
p0 + (p1 - p0).ln_one_minus_exp()
}
}
pub fn ln_cumsum_exp<I: IntoIterator<Item = LogProb>>(probs: I) -> ScanIter<I> {
probs.into_iter().scan(Self::ln_zero(), Self::scan_ln_add_exp)
}
pub fn ln_trapezoidal_integrate_exp<T, D>(density: &D, a: T, b: T, n: usize) -> LogProb where
T: Copy + Add<Output=T> + Sub<Output=T> + Div<Output=T> + Mul<Output=T>,
D: Fn(T) -> LogProb,
usize: ToFloat<T>,
f64: From<T>
{
let mut probs = linspace(a, b, n).dropping(1).dropping_back(1).map(|v| LogProb(*density(v) + 2.0f64.ln())).collect_vec();
probs.push(density(a));
probs.push(density(b));
let width = f64::from(b - a);
LogProb(*Self::ln_sum_exp(&probs) + width.ln() - (2.0 * (n - 1) as f64).ln())
}
pub fn ln_simpsons_integrate_exp<T, D>(density: &D, a: T, b: T, n: usize) -> LogProb where
T: Copy + Add<Output=T> + Sub<Output=T> + Div<Output=T> + Mul<Output=T>,
D: Fn(T) -> LogProb,
usize: ToFloat<T>,
f64: From<T>
{
assert!(n % 2 == 1, "n must be odd");
let mut probs = linspace(a, b, n).enumerate().dropping(1).dropping_back(1).map(|(i, v)| {
let weight = (2 + (i % 2) * 2) as f64;
LogProb(*density(v) + weight.ln())
}).collect_vec();
probs.push(density(a));
probs.push(density(b));
let width = f64::from(b - a);
LogProb(*Self::ln_sum_exp(&probs) + width.ln() - ((n - 1) as f64).ln() - 3.0f64.ln())
}
fn scan_ln_add_exp(s: &mut LogProb, p: LogProb) -> Option<LogProb> {
*s = s.ln_add_exp(p);
Some(*s)
}
}
impl From<LogProb> for Prob {
fn from(p: LogProb) -> Prob {
Prob(p.exp())
}
}
impl From<PHREDProb> for Prob {
fn from(p: PHREDProb) -> Prob {
Prob(10.0f64.powf(-*p / 10.0))
}
}
impl From<Prob> for LogProb {
fn from(p: Prob) -> LogProb {
LogProb(p.ln())
}
}
impl From<PHREDProb> for LogProb {
fn from(p: PHREDProb) -> LogProb {
LogProb(*p * PHRED_TO_LOG_FACTOR)
}
}
impl From<Prob> for PHREDProb {
fn from(p: Prob) -> PHREDProb {
PHREDProb(-10.0 * p.log10())
}
}
impl From<LogProb> for PHREDProb {
fn from(p: LogProb) -> PHREDProb {
PHREDProb(*p * LOG_TO_PHRED_FACTOR)
}
}
impl Default for LogProb {
fn default() -> LogProb {
LogProb::ln_zero()
}
}
impl Default for PHREDProb {
fn default() -> PHREDProb {
PHREDProb::from(Prob(0.0))
}
}
quick_error! {
#[derive(Debug)]
pub enum ProbError {
InvalidProb(value: f64) {
description("invalid probability")
display("probabilty {} not in interval [0,1]", value)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use itertools::Itertools;
#[test]
fn test_sum() {
let probs = [LogProb::ln_zero(), LogProb::ln_one(), LogProb::ln_zero()];
assert_eq!(LogProb::ln_sum_exp(&probs), LogProb::ln_one());
}
#[test]
fn test_empty_sum() {
assert_eq!(LogProb::ln_sum_exp(&[]), LogProb::ln_zero());
}
#[test]
fn test_cumsum() {
let probs = vec![LogProb::ln_zero(), LogProb(0.01f64.ln()), LogProb(0.001f64.ln())];
assert_eq!(LogProb::ln_cumsum_exp(probs).collect_vec(),
[LogProb::ln_zero(), LogProb(0.01f64.ln()), LogProb(0.011f64.ln())]);
}
#[test]
fn test_sub() {
assert_eq!(LogProb::ln_one().ln_sub_exp(LogProb::ln_one()), LogProb::ln_zero());
assert_relative_eq!(*LogProb::ln_one().ln_sub_exp(LogProb(0.5f64.ln())), *LogProb(0.5f64.ln()));
}
#[test]
fn test_one_minus() {
assert_eq!(LogProb::ln_zero().ln_one_minus_exp(), LogProb::ln_one());
assert_eq!(LogProb::ln_one().ln_one_minus_exp(), LogProb::ln_zero());
}
#[test]
fn test_trapezoidal_integrate() {
let density = |_| LogProb(0.1f64.ln());
let prob = LogProb::ln_trapezoidal_integrate_exp(&density, 0.0, 10.0, 5);
assert_relative_eq!(*prob, *LogProb::ln_one(), epsilon=0.0000001);
}
#[test]
fn test_simpsons_integrate() {
let density = |_| LogProb(0.1f64.ln());
let prob = LogProb::ln_simpsons_integrate_exp(&density, 0.0, 10.0, 5);
assert_relative_eq!(*prob, *LogProb::ln_one(), epsilon=0.0000001);
}
}