-
Notifications
You must be signed in to change notification settings - Fork 0
/
success_accumulator.py
62 lines (54 loc) · 2.12 KB
/
success_accumulator.py
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
"""
Utility for accumulating the probability of a sequence of events.
"""
class SuccessAccumulator:
""" Utility for accumulating success probabilities for a sequence of events.
It helps reducing code clutter when computing
P[w] = P[w0] + P[f0 and w1] + P[f0 and f1 and w2] + ...
= P[w0] + P[w1|f0] * P[f0] + P[w2|f0 and f1] P[f0 and f1] + ...
One only needs to provide the values of P[wi|fi-1 and ... and f0].
TESTS:
>>> # tests initialisation
>>> sa = SuccessAccumulator(target_probability=.6)
>>> assert(sa.success_probability() == 0)
>>> assert(sa.failure_probability() == 1)
>>> # tests some accumulation
>>> sa.accumulate(0.5)
False
>>> sa.accumulate(0.2)
True
>>> assert(sa.success_probability() == 0.6)
>>> assert(sa.failure_probability() == 0.4)
>>> sa.accumulate(1)
True
>>> assert(sa.success_probability() == 1)
>>> assert(sa.failure_probability() == 0)
>>> # test accumulating lots of events, should not raise ValueError
>>> sa = SuccessAccumulator()
>>> import random
>>> for _ in range(100): _ = sa.accumulate(random.random())
"""
def __init__(self, target_probability=1):
self.p_win = 0
self.target = target_probability
def accumulate(self, p):
""" Method for providing the values of P[wi|fi-1 and ... and f0].
Accumulating p = 1 will cause the resulting success probability to be 1.
"""
if p < 0 or p > 1:
raise ValueError(
f"Input additional probability outside of valid range {p}")
p_fail = 1 - self.p_win
self.p_win += p_fail * p
if self.p_win < 0 or self.p_win > 1:
raise ValueError(
f"Success probability outside of valid range: {self.p_win}")
return self.p_win >= self.target
def success_probability(self):
""" Getter for value of p_win.
"""
return self.p_win
def failure_probability(self):
""" Getter for value of 1 - p_win.
"""
return 1 - self.p_win