-
Notifications
You must be signed in to change notification settings - Fork 6
/
randomgen.py
executable file
·5306 lines (4981 loc) · 196 KB
/
randomgen.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
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Sample code for the article "Randomization and Sampling Methods"
www.codeproject.com/Articles/1190459/Random-Number-Generation-Methods
Written by Peter O.
Any copyright to this work is released to the Public Domain.
In case this is not possible, this work is also
licensed under Creative Commons Zero (CC0):
creativecommons.org/publicdomain/zero/1.0/
"""
# TODO: Use betadist's PSRN methods here somehow
import math
import random
from fractions import Fraction
from betadist import *
_SIGBITS = 53
_FLOAT_MAX = 1.7976931348623157e308
def _mean(list):
if len(list) <= 1:
return 0
xm = list[0]
i = 1
while i < len(list):
c = list[i]
i += 1
cxm = c - xm
xm += cxm * 1.0 / i
return xm
def _variance(list):
if len(list) <= 1:
return 0
xm = list[0]
xs = 0
i = 1
while i < len(list):
c = list[i]
i += 1
cxm = c - xm
xm += cxm * 1.0 / i
xs += cxm * (c - xm)
return xs * 1.0 / (len(list) - 1)
def _tableInterpSearch(table, x, censor=False):
# Effective length is the length of table minus 1
tablelen = len(table) - 1
left = 0
right = tablelen - 1
while left <= right:
index = int((left + right) / 2)
c = table[index]
n = table[index + 1]
if x >= c[0] and x < n[0]:
interp = (x - c[0]) * 1.0 / (n[0] - c[0])
return c[1] + (n[1] - c[1]) * interp
if x > c[0]:
left = index + 1
continue
right = index - 1
continue
if censor:
if x <= table[0][0]:
return table[0][1]
if x >= table[tablelen][0]:
return table[tablelen][1]
return None
def numericalTable(func, x, y, n=100):
ret = [x + (y - x) * (i * 1.0 / n) for i in range(n + 1)]
return [[func(b), b] for b in ret]
class VoseAlias:
"""
Implements Vose's version of the alias sampler, which chooses a random variate in [0, n)
where the probability that each number is chosen is weighted. The 'weights' is the
list of weights each 0 or greater; the higher the weight, the greater
the probability. This sampler supports integer or non-integer weights.
Reference:
Vose, Michael D. "A linear algorithm for generating random variates with a given
distribution." IEEE Transactions on software engineering 17, no. 9 (1991): 972-975.
"""
def __init__(self, weights):
# Vose's alias method for large n and nonnegative
# weights. This method has a non-trivial setup,
# but a linear-time sampling step in n.
prob = [0 for _ in weights]
alias = [0 for _ in weights]
tmp = [p * len(weights) for p in weights]
mn = min(weights)
mx = max(weights)
ms = sum(weights)
small = [i for i in range(len(tmp)) if tmp[i] < ms]
large = [i for i in range(len(tmp)) if tmp[i] >= ms]
sc = len(small)
lc = len(large)
while sc > 0 and lc > 0:
lv = small[sc - 1]
g = large[lc - 1]
prob[lv] = tmp[lv]
alias[lv] = g
overhead = (tmp[g] + tmp[lv]) - ms
if overhead < ms:
small[sc - 1] = g
lc -= 1
else:
sc -= 1
tmp[g] = overhead
for i in range(sc):
prob[small[i]] = ms
for i in range(lc):
prob[large[i]] = ms
if len(prob) != len(weights):
raise ValueError("Internal error")
if len(alias) != len(weights):
raise ValueError("Internal error")
self.total = ms
self.prob = prob
self.alias = alias
def next(self, randgen):
d = randgen.rndintexc(len(self.prob))
da = self.alias[d]
if d == da:
return d
tsample = (
randgen.rndintexc(self.total)
if int(self.total) == self.total
else randgen.rndrangemaxexc(0, self.total)
)
return d if tsample < self.prob[d] else da
class BringmannLarsen:
"""
Implements Bringmann and Larsen's sampler, which chooses a random variate in [0, n)
where the probability that each number is chosen is weighted. The 'weights' is the
list of weights each 0 or greater; the higher the weight, the greater
the probability. This sampler supports only integer weights.
This is a succinct (space-saving) data structure for this purpose.
Reference:
K. Bringmann and K. G. Larsen, "Succinct Sampling from Discrete
Distributions", In: Proc. 45th Annual ACM Symposium on Theory
of Computing (STOC'13), 2013.
"""
def __init__(self, weights):
w = 32
wc = w - 12
totalWeights = sum(weights)
n = len(weights)
if totalWeights < 0:
raise ValueError("Sum of weights is negative")
self.large = totalWeights >= (1 << (wc - 1)) * n
# NOTE: Storing the max is not strictly necessary,
# but helps avoid high rejection rates
self.maxWeight = max(weights)
if not self.large:
bitlength = 0
self.bits = 0
self.shorts = 0
self.n = n
bs = 0
for i in range(n):
if weights[i] < (1 << wc):
self.bits |= weights[i] << bs
bs += wc
else:
if weights[i] >= (1 << w):
raise ValueError
self.bits |= weights[i] << bs
self.shorts |= 1 << i
bs += w
else:
self.weights = [x for x in weights]
def _ranki(self, i):
ret = 0
for j in range(i):
ret += (self.shorts >> j) & 1
return ret
def next(self, randgen):
w = 32
wc = w - 12
if self.large:
while True:
v = randgen.rndintexc(len(self.weights))
# NOTE: Using stored max weight instead of a constant 2^w
# (which the paper uses for space saving), to avoid
# high rejection rates. However, the algorithm is
# still correct in either case (except in the latter case
# when self.maxWeight >= 2^w).
if randgen.zero_or_one(self.weights[v], self.maxWeight) == 1:
return v
else:
while True:
v = randgen.rndintexc(self.n)
k = self._ranki(v)
bp = k * w + (v - k) * wc
bl = w if self._ranki(v + 1) > k else wc
weight = (self.bits >> bp) & ((1 << bl) - 1)
# NOTE: See note above
if randgen.zero_or_one(weight, self.maxWeight) == 1:
return v
class FastLoadedDiceRoller:
"""
Implements the Fast Loaded Dice Roller, which chooses a random variate in [0, n)
where the probability that each number is chosen is weighted. The 'weights' is the
list of weights each 0 or greater; the higher the weight, the greater
the probability. This sampler supports only integer weights.
Reference: Saad, F.A., Freer C.E., et al. "The Fast Loaded Dice Roller: A
Near-Optimal Exact Sampler for Discrete Probability Distributions", in
_AISTATS 2020: Proceedings of the 23rd International Conference on Artificial
Intelligence and Statistics, Proceedings of Machine Learning Research_ 108,
Palermo, Sicily, Italy, 2020.
"""
def __init__(self, weights):
self.n = len(weights)
if self.n == 1:
return
weightBits = 0
totalWeights = sum(weights)
if totalWeights < 0:
raise ValueError("Sum of weights is negative")
if totalWeights == 0:
raise ValueError("Sum of weights is zero")
tmp = totalWeights - 1
while tmp > 0:
tmp >>= 1
weightBits += 1
lasta = (1 << weightBits) - totalWeights
self.leavesAndLabels = [
[0 for i in range(weightBits)] for j in range(self.n + 2)
]
shift = weightBits - 1
for j in range(weightBits):
level = 1
for i in range(self.n + 1):
ai = lasta if i == self.n else weights[i]
if ai < 0:
raise ValueError
leaf = (ai >> shift) & 1
if leaf > 0:
# NOTE: Labels start at 1
self.leavesAndLabels[0][j] += leaf
self.leavesAndLabels[level][j] = i + 1
level += 1
shift -= 1
def codegen(self, name="sample_discrete"):
"""Generates standalone Python code that samples
from the distribution modeled by this class.
Idea from Leydold, et al.,
"An Automatic Code Generator for
Nonuniform Random Variate Generation", 2001.
- name: Method name. Default: 'sample_discrete'."""
ret = "import random\n\n"
ret += "TABLE_" + name + " = ["
for i in range(len(self.leavesAndLabels)):
if i > 0:
ret += ", "
ret += "%s" % (str(self.leavesAndLabels[i]),)
ret += "]\n\n"
ret += "def " + name + "():\n"
if self.n <= 1:
ret += "return 0\n\n"
else:
ret += " x = 0\n"
ret += " y = 0\n"
ret += " while True:\n"
ret += " x = random.randint(0, 1) | (x << 1)\n"
ret += " leaves = TABLE_" + name + "[0][y]\n"
ret += " if x < leaves:\n"
ret += " label = TABLE_" + name + "[x + 1][y]\n"
ret += " if label <= %d:\n" % (self.n)
ret += " return label - 1\n"
ret += " x = 0\n"
ret += " y = 0\n"
ret += " else:\n"
ret += " x -= leaves\n"
ret += " y += 1\n"
return ret
def next(self, randgen):
if self.n == 1:
return 0
x = 0
y = 0
while True:
x = randgen.randbit() | (x << 1)
leaves = self.leavesAndLabels[0][y]
if x < leaves:
label = self.leavesAndLabels[x + 1][y]
if label <= self.n:
# NOTE: The number of bits consumed
# by this call (A), as well as
# (label - 1) (B), are two separate
# random variables that could be
# recycled via a randomness extraction
# method to generate additional uniform
# random bits, as explained by L.
# Devroye and C. Gravel, arXiv:1502.02539 [cs. IT]
# More specifically, the expected number of bits
# that can be extracted this way is the amount
# of randomness in A given that this call returns a
# specific label.
return label - 1
x = 0
y = 0
else:
x -= leaves
y += 1
class SortedAliasMethod:
"""Implements a weighted sampling table
where each weight must be in sorted
order (ascending or descending).
When many entries are in the table,
the initialization is faster than with
FastLoadedDiceRoller or VoseAlias. Reference:
K. Bringmann and K. Panagiotou, "Efficient Sampling
Methods for Discrete Distributions." In: Proc. 39th
International Colloquium on Automata, Languages,
and Programming (ICALP'12), 2012.
- p: List of weights, in sorted order (ascending or
descending).
"""
def __init__(self, p):
ps = sum(p)
asc = True
if p[0] > p[1] or p[0] > p[len(p) - 1]:
asc = False
for i in range(len(p) - 1):
if p[i] < p[i + 1]:
raise ValueError("Not in sorted order")
else:
for i in range(len(p) - 1):
if p[i] > p[i + 1]:
raise ValueError("Not in sorted order")
q = []
k = 0
self.asc = asc
self.n = len(p)
while ((1 << k) - 1) < len(p):
qk = min(2 << k, len(p) + 1) - (1 << k)
pIndex = (1 << k) - 1
if asc:
pIndex = self.n - 1 - pIndex
qk *= Fraction(p[pIndex], ps)
q.append(int(qk * ps))
k += 1
self.alias = randomgen.FastLoadedDiceRoller(q)
self.p = [x for x in p]
def next(self, rg):
while True:
k = self.alias.next(rg)
rmn = 1 << k
rmx = min((2 << k) - 1, self.n)
ret = rg.rndintrange(rmn, rmx) - 1
pIndex = (1 << k) - 1
if self.asc:
ret = self.n - 1 - ret
pIndex = self.n - 1 - pIndex
if rg.zero_or_one(self.p[ret], self.p[pIndex]) == 1:
return ret
class OptimalSampler:
"""
Implements a sampler which chooses a random variate in [0, n)
where the probability that each number is chosen is weighted. The 'weights' is the
list of weights each 0 or greater; the higher the weight, the greater
the probability. This sampler supports only integer weights, but the sampler is
entropy-optimal as long as the sum of those weights is of the form 2^k or 2^k-2^m.
Reference: Feras A. Saad, Cameron E. Freer, Martin C. Rinard, and Vikash K. Mansinghka.
Optimal Approximate Sampling From Discrete Probability Distributions. Proc.
ACM Program. Lang. 4, POPL, Article 36 (January 2020), 33 pages.
"""
def __init__(self, m):
s = sum(m)
if s <= 0:
raise ValueError
if len(m) == 1:
# degenerate
self.k = self.l = 0
self.rej = -1
self.lin = [-1]
else:
pm, self.l, self.rej = self._preparematrix(m)
self.k = s.bit_length()
leaves = {}
i = 2
for x in range(self.k):
for y in range(len(pm)):
if ((pm[y] >> (self.k - 1 - x)) & 1) != 0:
leaves[i] = y + 1
i -= 1
i = 2 + (i << 1)
root = self._tree(0, [], leaves)
self.lin = []
self._pack(self.lin, root, 0)
def next(self, rg):
if len(self.lin) == 1:
return 0
x = 0
while True:
x = self.lin[x + rg.randbit()]
if self.lin[x] < 0:
# Subtract by 1 because we're returning
# values in [0, n)
ret = (-self.lin[x]) - 1
if ret == self.rej:
continue
return ret
def nextFromMatrix(self, pm, rg):
# Alternate sampler that samples directly
# from the probability matrix,
# rather than the encoded DDG tree. It is
# entropy-optimal as long as there is no
# rejection event.
if len(pm) == 1:
return 0
x = 0
y = 0
while True:
x = (x << 1) | rg.randbit()
for z in range(len(pm)):
x -= (pm[z] >> (self.k - 1 - y)) & 1
# Handle rejection event
if x == -1 and z == self.rej:
x = 0
y = -1
break
# Use z, not z+1, because we're returning
# values in [0, n)
if x == -1:
return z
y = self.l if (y == self.k - 1) else (y + 1)
def codegen(self, name="sample_discrete"):
"""Generates standalone Python code that samples
from the distribution modeled by this class.
Idea from Leydold, et al.,
"An Automatic Code Generator for
Nonuniform Random Variate Generation", 2001.
- name: Method name. Default: 'sample_discrete'."""
ret = "import random\n\n"
ret += "TABLE_" + name + " = ["
for i in range(len(self.lin)):
if i > 0:
ret += ", "
ret += "%s" % (self.lin[i],)
ret += "]\n\n"
ret += "def " + name + "():\n"
if self.lin == 1:
ret += " return 0\n\n"
else:
ret += " x = 0\n"
ret += " while True:\n"
ret += " x = TABLE_" + name + "[x + random.randint(0, 1)]\n"
ret += " if TABLE_" + name + "[x] < 0:\n"
if self.rej >= 0:
ret += " ret = (-TABLE_" + name + "[x]) - 1\n"
ret += " if ret == self.rej: continue\n"
ret += " return ret\n\n"
else:
ret += " return (-TABLE_" + name + "[x]) - 1\n\n"
return ret
def _pack(self, lin, node, o):
node[3] = o
wt = 0
if node[0] != None:
while o >= len(lin):
lin.append(0)
lin[o] = -node[0]
return o + 1
if (not node[1]) or (not node[2]):
raise ValueError
if node[1][3] != None:
while o >= len(lin):
lin.append(0)
lin[o] = node[1][3]
wt = o + 2
else:
while o >= len(lin):
lin.append(0)
lin[o] = o + 2
wt = self._pack(lin, node[1], o + 2)
if node[2][3] != None:
while o + 1 >= len(lin):
lin.append(0)
lin[o + 1] = node[2][3]
else:
while o + 1 >= len(lin):
lin.append(0)
lin[o + 1] = wt
wt = self._pack(lin, node[2], wt)
return wt
def _makeleaftable(self, p, k):
leaves = {}
i = 2
for x in range(k):
for y in range(len(p)):
if ((p[y] >> (k - 1 - x)) & 1) != 0:
leaves[i] = y + 1
i -= 1
i = 2 + (i << 1)
return leaves
def _tree(self, i, ancestors, leaves):
# sanity check
if i > (1 << (self.k + 3)):
raise ValueError
if i in leaves:
return [leaves[i], None, None, None] # Leaf node
else:
node = [None, None, None, None] # label, left, right, loc
level = (i + 1).bit_length() - 1
if level == self.l:
ancestors.append(node)
if level == self.k - 1 and not (2 * i + 2 in leaves):
node[2] = ancestors.pop()
else:
node[2] = self._tree(2 * i + 2, ancestors, leaves)
if level == self.k - 1 and not (2 * i + 1 in leaves):
node[1] = ancestors.pop()
else:
node[1] = self._tree(2 * i + 1, ancestors, leaves)
return node
def _preparematrix(self, m):
s = sum(m)
if s <= 0 or len(m) < 2:
raise ValueError
k = s.bit_length()
l = 0
rejectionEvent = -1
if s != (1 << k):
accept = False
acceptable = 1 << k
acceptableL = k
l = 1
while l < k:
if s == (1 << k) - (1 << l):
accept = True
break
elif s > (1 << k) - (1 << l):
break
else:
acceptableL = l
acceptable = (1 << k) - (1 << l)
l += 1
if not accept:
# Add a "rejection" event (suggested
# for the Fast Loaded Dice Roller but not
# in optimal approximate sampling paper,
# which supports only certain sums of
# weights)
l = acceptableL
rejectionEvent = acceptable - s
b = []
mv = len(m) + 1 if rejectionEvent >= 0 else len(m)
for i in range(mv):
mi = rejectionEvent if i >= len(m) else m[i]
x = 0
y = 0
if l == k:
x = mi
elif l == 0:
y = mi
else:
msk = (1 << (k - l)) - 1
x = mi // msk
y = mi - msk * x
xy = (x << (k - l)) | y
if xy >= (1 << k):
raise ValueError
b.append(xy)
return [b, l, len(m) if rejectionEvent >= 0 else -1]
class _BinomialAliasTable:
def __init__(self, aliases, entries, n):
self.aliases = aliases
if len(entries) != len(aliases):
raise ValueError
if aliases[len(aliases) - 1] != -1:
raise ValueError
self.failureEntry = entries[len(entries) - 1]
self.failureCumul = []
self.failureRaw = []
self.failureAlias = None
self.failureCc = 1
self.n = n
self.entrymap = None
# self.entrymap={}
# for i in range(len(aliases)): self.entrymap[aliases[i]]=entries[i]
self.entries = FastLoadedDiceRoller(entries)
def _bitcount(self, x):
r = 0
while x > 0:
r += 1
x >>= 1
return r
def _verify(self, k, c, sh):
if self.entrymap != None:
em = 0
if k in self.entrymap:
em = self.entrymap[k]
if (c >> sh) != em:
raise ValueError
def _buildFailureAliasesIfNeeded(self):
if self.failureAlias == None and len(self.failureRaw) > self.n // 2 + 1:
olen = len(self.failureRaw)
clen = olen
for i in range(olen, self.n + 1):
self.failureRaw.append(self.failureRaw[self.n - i])
clen += 1
self.failureAlias = FastLoadedDiceRoller(self.failureRaw)
self.failureRaw = None
self.failureCumul = None
def next(self, rg):
v = self.aliases[self.entries.next(rg)]
if v >= 0:
return v
if self.failureAlias != None:
return self.failureAlias.next(rg)
return self._sampleFromFailure(rg)
def _sampleFromFailure(self, rg):
# Sample from the failure distribution
# print("sampling from failure")
s = max(16, self._bitcount(self.n))
failurevalues = self.failureEntry << (self.n - s)
cf = (1 << (self.n - s)) - 1
failureCumulLen = len(self.failureCumul)
if failureCumulLen <= 0:
self.failureCumul.append(1)
self.failureRaw.append(1)
self.failureCc = 1
failureCumulLen = 1
failureRate = rg.rndint(failurevalues - 1)
totalcv = 1
if failureRate < totalcv:
return 0
# Build the row
for i in range(1, self.n + 1):
if failureCumulLen == i:
self.failureCc = self.failureCc * (self.n - (i - 1)) // i
# self._verify(i, self.failureCc, self.n - s)
ccf = self.failureCc & cf
totalcv = self.failureCumul[i - 1] + ccf
# print("i=%d fcc=%x/%x tcv=%x" % (i, self.failureCc, ccf, totalcv))
self.failureCumul.append(totalcv)
self.failureRaw.append(ccf)
failureCumulLen += 1
elif failureCumulLen < i:
raise ValueError("should not happen")
else:
totalcv = self.failureCumul[i]
if failureRate < totalcv:
# self._buildFailureAliasesIfNeeded()
# print("sampled %d" % (i))
return i
elif totalcv > failurevalues:
raise ValueError("totalcv=%x expected=%x" % (totalcv, failurevalues))
if totalcv != failurevalues:
raise ValueError("totalcv=%x expected=%x" % (totalcv, failurevalues))
raise ValueError("should not happen")
class PascalTriangle:
"""Generates the rows of Pascal's triangle, or the
weight table for a binomial(n,1/2) distribution."""
def __init__(self):
self.table = []
self.rownumber = 0
def row(self):
"""Gets the row number of the row that will be generated
the next time _next_ is called."""
return self.rownumber
def _bitcount(self, x):
r = 0
while x > 0:
r += 1
x >>= 1
return r
def _verifyAliasTable(self, table, row):
# Verify whether an alias table with less
# than full precision is correct. 'row' is the
# corresponding Pascal triangle row.
n = len(table) - 1
s = max(16, self._bitcount(n))
tablesum = sum(table)
if tablesum > (1 << s):
raise ValueError
if len(table) != len(row):
raise ValueError
for i in range(0, len(row)):
coarse = table[i]
fine = row[i]
cr = Fraction(coarse, 1 << s)
fr = Fraction(fine, 1 << n)
ls = fr - cr
if ls < 0 or ls > Fraction(1, 1 << s):
raise ValueError
def _nthOfDoubleRowFromRow(self, row):
# Calculates nth entry (starting from 0)
# of the Pascal triangle
# row for 2*n given a Pascal triangle row for n
# (where n is calculated as len(row)-1).
r = 0
n = len(row) - 1
for i in range(0, n + 1):
r += row[i] * row[n - i]
return r
def _buildAliasTable(self, prob, n, fullPrecision=False):
# prob is (n/2)th entry (starting at 0) of
# the Pascal triangle row for n. The entry 'prob'
# is full precision regardless of the setting
# for 'fullPrecision'.
half = n >> 1
s = max(16, self._bitcount(n))
odd = n % 2 == 1
oddadd = 1 if odd else 0
sguard = s * 2 # should be at least s+ceil(log(n))
if fullPrecision:
s = n
sguard = n # full precision
phalf = prob >> (n - sguard)
h_s = Fraction(phalf, 1 << sguard)
aliastable = [0 for i in range(n + 1)]
aliastable[half] = int(h_s * (1 << s))
if odd:
aliastable[half + 1] = aliastable[half]
for i in range(1, half + 1):
delta_t_num = half + 1 - i
delta_t_den = half + i
hsa = h_s * delta_t_num / delta_t_den
hsafloor = int(hsa * (1 << s))
if hsafloor == 0:
break
aliastable[half - i] = hsafloor
aliastable[half + i + oddadd] = hsafloor
h_s = hsa
return aliastable
def getrow(self, desiredRow):
"""Calculates an arbitrary row of Pascal's triangle."""
r = [1 for i in range(desiredRow + 1)]
r[0] = 1
c = 1
# Build half of the row
for i in range(1, desiredRow // 2 + 1):
c = c * (desiredRow - (i - 1)) // i
r[i] = c
# Reflect onto the other half
lenr = len(r)
for i in range(desiredRow // 2 + 1):
r[lenr - 1 - i] = r[i]
return r
def _buildAliasTable2(self, prob, n):
# prob is (n/2)th entry (starting at 0) of
# the Pascal triangle row for n. The entry 'prob'
# is full precision.
half = n >> 1
s = max(16, self._bitcount(n))
odd = n % 2 == 1
oddadd = 1 if odd else 0
sguard = s * 2 # should be at least s+ceil(log(n))
if n < sguard:
raise ValueError
phalf = prob >> (n - sguard)
h_s = Fraction(phalf, 1 << sguard)
aliases = []
aliasentries = []
aliases.append(half)
halfentry = int(h_s * (1 << s))
aliasentries.append(halfentry)
totalentries = halfentry
if odd:
aliases.append(half + 1)
aliasentries.append(halfentry)
totalentries += halfentry
for i in range(1, half + 1):
delta_t_num = half + 1 - i
delta_t_den = half + i
hsa = h_s * delta_t_num / delta_t_den
# print([math.log(hsa.denominator),math.log(h_s.denominator)])
hsafloor = int(hsa * (1 << s))
if hsafloor < 0:
raise ValueError
if hsafloor == 0:
break
aliases.append(half - i)
aliases.append(half + i + oddadd)
aliasentries.append(hsafloor)
aliasentries.append(hsafloor)
totalentries += hsafloor * 2
# h_s = hsa # -- known to be correct
h_s = Fraction(int(hsa * (1 << sguard)), 1 << sguard)
aliases.append(-1)
failureentry = (1 << s) - totalentries
# print(aliasentries)
# print(aliases)
# print([totalentries, failureentry])
if failureentry < 0:
raise ValueError
aliasentries.append(failureentry)
return _BinomialAliasTable(aliases, aliasentries, n)
def aliasinfo(self, desiredRow):
r = self.getrow(desiredRow)
if desiredRow <= 16:
# Use simple alias table to avoid overhead
return FastLoadedDiceRoller(r)
return self._buildAliasTable2(r[desiredRow // 2], desiredRow)
def nextto(self, desiredRow):
"""Generates the row of Pascal's triangle with the given row number,
skipping all rows in between. The return value is a list of
row-number-choose-k values."""
if self.rownumber - 1 == desiredRow:
# Already at desired row
return [x for x in self.table]
if self.rownumber > desiredRow:
raise ValueError
self.table = self.getrow(desiredRow)
self.rownumber = desiredRow + 1
return [x for x in self.table]
def next(self):
"""Generates the next row of Pascal's triangle, starting with
row 0. The return value is a list of row-number-choose-k
values."""
x = self.table
xr = [
1 if i == 0 or i == len(x) else x[i] + x[i - 1] for i in range(len(x) + 1)
]
self.table = xr
self.rownumber += 1
return [x for x in self.table]
class _FractionBinaryExpansion:
def __init__(self, frac):
self.frac = frac
self.fracnum = frac.numerator
self.fracden = frac.denominator
self.pt = 1
def reset(self):
"""Resets this object to the first bit in the binary expansion."""
self.fracnum = frac.numerator
self.fracden = frac.denominator
self.pt = 1
def eof(self):
"""Returns True if the end of the binary expansion was reached; False otherwise."""
return self.fracnum == 0
def nextbit(self):
"""Reads the next bit in the binary expansion."""
if self.fracnum == 0:
return 0
# Determine whether frac >= 2**-pt
cmpare = (self.fracnum << self.pt) >= self.fracden
if self.tmpfrac >= self.px:
# Subtract 2**-pt from frac
self.fracnum = (self.fracnum << self.pt) - self.fracden
self.fracden <<= self.pt
self.pt += 1
return 1
else:
self.pt += 1
return 0
class _FloatBinaryExpansion:
def __init__(self, frac):
self.frac = frac
self.tmpfrac = frac
self.px = 0.5
def reset(self):
"""Resets this object to the first bit in the binary expansion."""
self.tmpfrac = frac
self.px = 0.5
def eof(self):
"""Returns True if the end of the binary expansion was reached; False otherwise."""
return self.tmpfrac == 0
def nextbit(self):
"""Reads the next bit in the binary expansion."""
if self.tmpfrac == 0:
return 0
if self.tmpfrac >= self.px:
self.tmpfrac -= self.px
self.px /= 2
return 1
else:
self.px /= 2
return 0
class BinaryExpansion:
def __init__(self, arr, zerosAtEnd=False):
"""
Binary expansion of a real number in [0, 1], initialized
from an array of zeros and ones expressing the binary
expansion.
The first binary digit is the half digit, the second
is the quarter digit, the third is the one-eighth digit,
and so on. Note that the number 1 can be
expressed by passing an empty array and specifying
zerosAtEnd = False, and the number 0 can be
expressed by passing an empty array and specifying
zerosAtEnd = True.
arr - Array indicating the initial digits of the binary
expansion.
zerosAtEnd - Indicates whether the binary expansion
is expressed as 0.xxx0000... or 0.yyy1111... (e.g., 0.1010000...
vs. 0.1001111.... Default is the latter case (False).
"""
self.arr = [x for x in arr]
self.zerosAtEnd = zerosAtEnd
if sum(self.arr) > 0 and not zerosAtEnd:
# "Subtract" 1 from the binary expansion
i = len(self.arr) - 1
while i >= 0:
self.arr[i] ^= 1
if self.arr[i] == 0:
break
i -= 1
self.index = 0
def eof(self):
"""Returns True if the end of the binary expansion was reached; False otherwise."""
return self.zerosAtEnd and self.index >= len(self.arr)
def entropy(self):
# Binary entropy
v = self.value()
return v * math.log2(1.0 / v)
def get(f):
"""Creates a binary expansion object from a fraction, 'int', or
'float' in the interval [0, 1]; returns 'f' unchanged, otherwise."""
if f == 0:
return BinaryExpansion([], True)
if f == 1:
return BinaryExpansion([], False)
if isinstance(f, Fraction):
return BinaryExpansion.fromFraction(f)
elif isinstance(f, float):
return BinaryExpansion.fromFloat(f)
else:
return f
def getOrReset(f):
"""Creates a binary expansion object from a fraction, 'int', or
'float' in the interval [0, 1]; resets 'f' (calls its reset method) otherwise.
"""
if f == 0:
return BinaryExpansion([], True)
if f == 1:
return BinaryExpansion([], False)
if isinstance(f, Fraction):
return BinaryExpansion.fromFraction(f)
elif isinstance(f, float):
return BinaryExpansion.fromFloat(f)
else:
f.reset()
return f
def fromFraction(f):
"""Creates a binary expansion object from a fraction in the