classAliasSampling: """Helper function for performing sampling.""" def__init__(self, prob): self.n = len(prob) self.U = np.array(prob) * self.n self.K = [i for i inrange(len(prob))] overfull, underfull = [], [] for i, U_i inenumerate(self.U): if U_i > 1: overfull.append(i) elif U_i < 1: underfull.append(i) whilelen(overfull) andlen(underfull): i, j = overfull.pop(), underfull.pop() self.K[j] = i self.U[i] = self.U[i] - (1 - self.U[j]) if self.U[i] > 1: overfull.append(i) elif self.U[i] < 1: underfull.append(i)
defsampling(self, n=1): x = np.random.rand(n) i = np.floor(self.n * x) y = self.n * x - i i = i.astype(np.int32) res = [i[k] if y[k] < self.U[i[k]] else self.K[i[k]] for k inrange(n)] if n == 1: return res[0] else: return res