-
Notifications
You must be signed in to change notification settings - Fork 271
/
Copy pathrandom_.py
95 lines (70 loc) · 2.09 KB
/
random_.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
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
import random
import numpy as np
from numpy.random import choice
from axelrod.action import Action
C, D = Action.C, Action.D
def seed(seed_):
"""Sets a seed"""
random.seed(seed_)
np.random.seed(seed_)
def random_choice(p: float = 0.5) -> Action:
"""
Return C with probability `p`, else return D
No random sample is carried out if p is 0 or 1.
Parameters
----------
p : float
The probability of picking C
Returns
-------
axelrod.Action
"""
if p == 0:
return D
if p == 1:
return C
r = random.random()
if r < p:
return C
return D
def random_flip(action: Action, threshold: float) -> Action:
"""
Return flipped action with probability `threshold`
No random sample is carried out if threshold is 0 or 1.
Parameters
----------
action:
The action to flip or not
threshold : float
The probability of flipping action
Returns
-------
axelrod.Action
"""
if random_choice(threshold) == C:
return action.flip()
return action
def randrange(a: int, b: int) -> int:
"""Python 2 / 3 compatible randrange. Returns a random integer uniformly
between a and b (inclusive)"""
c = b - a
r = c * random.random()
return a + int(r)
def random_vector(size):
"""Create a random vector of values in [0, 1] that sums to 1."""
vector = np.random.random(size)
return vector / np.sum(vector)
class Pdf(object):
"""A class for a probability distribution"""
def __init__(self, counter):
"""Take as an instance of collections.counter"""
self.sample_space, self.counts = zip(*counter.items())
self.size = len(self.sample_space)
self.total = sum(self.counts)
self.probability = list([v / self.total for v in self.counts])
def sample(self):
"""Sample from the pdf"""
index = choice(a=range(self.size), p=self.probability)
# Numpy cannot sample from a list of n dimensional objects for n > 1,
# need to sample an index.
return self.sample_space[index]