-
Notifications
You must be signed in to change notification settings - Fork 6
/
betadist.py
executable file
·5729 lines (5230 loc) · 187 KB
/
betadist.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
#
# Written by Peter O. Any copyright to this file is released to the Public Domain.
# In case this is not possible, this file is also licensed under Creative Commons Zero
# (https://creativecommons.org/publicdomain/zero/1.0/).
#
import random
try:
import bernoulli
import randomgen
except:
pass
import math
from fractions import Fraction
def betabin(k, psi, rho, cpsi, m=5):
ret = math.comb(m - 1, k - 1)
for i in range(k - 1):
ret *= (psi - 1) * rho / (m - 1) + i * (cpsi - rho)
for j in range(m - k):
ret *= (m - psi) * rho / (m - 1) + j * (cpsi - rho)
return ret
def genscore_mean_var(mean, vari, m=5):
# Generalized score distribution, parameterized by mean and variance
psi = mean
vmin = (-((-psi) // 1) - psi) * (psi - psi // 1) # Minimum possible variance
vmax = (psi - 1) * (m - psi) # Maximum possible variance
if vari < vmin or vari > vmax:
raise ValueError
if vmin == vmax:
return genscore(psi, 0, m=m)
else:
return genscore(psi, 1 - (vari - vmin) / (vmax - vmin), m=m)
def genscore(psi, rho, m=5):
# Generalized score distribution (GSD).
# Return value is an integer in [1, m].
# psi = mean; rho = confidence parameter in [0, 1], where the higher
# rho is, the smaller the variance; m = maximum integer.
# Reference:
# Bogdan Ćmiel, Nawała, Jakub, Lucjan Janowski, and Krzysztof Rusek. "Generalised Score Distribution: Underdispersed Continuation of the Beta-Binomial Distribution" arXiv preprint arXiv:2204.10565v1 [stat.AP] (2022).
# Designed to cover all possibilities of mean and variance for distributions
# taking values in {1, 2, ..., m}.
psi = Fraction(psi)
rho = Fraction(rho)
if rho < 0 or rho > 1 or psi < 1 or psi > m:
raise ValueError
if m == 2:
# Bernoulli distribution, not formally part of the GSD.
return 1 + randBernoulli(psi - 1)
if m // 1 != m or m < 2:
raise ValueError
vmin = (-((-psi) // 1) - psi) * (psi - psi // 1) # Minimum possible variance
vmax = (psi - 1) * (m - psi) # Maximum possible variance
# Then the return value's variance is rho*vmin+(1-rho)*vmax.
cpsi = ((m - 2) * vmax) / ((m - 1) * (vmax - vmin))
if rho < cpsi:
# Alternative implementation (which relies on
# floating point numbers due to random.betavariate):
# a = (psi - 1) * rho / ((m - 1) * (cpsi - rho))
# b = (m - psi) * rho / ((m - 1) * (cpsi - rho))
# p = random.betavariate(a, b)
# return 1 + sum(randBernoulli(p) for i in range(m - 1))
weights = [betabin(i, psi, rho, cpsi) for i in range(1, m + 1)]
maxweight = max(weights)
while True:
ret = random.randint(0, len(weights) - 1)
if randBernoulli(weights[ret] / maxweight) == 1:
return ret + 1
else:
if randBernoulli((rho - cpsi) / (1 - cpsi)) == 1:
if psi == psi // 1: # psi//1 = floor(psi)
return psi
prob = -((-psi) // 1) - psi
if randBernoulli(prob) == 1:
return psi // 1
else:
return -((-psi) // 1) # -((-psi)//1) = ceil(psi)
else:
return 1 + sum(randBernoulli((psi - 1) / (m - 1)) for i in range(m - 1))
def randBernoulli(f):
if f == 1:
return 1
if f == 0:
return 0
if isinstance(f, Fraction):
return random.randint(0, f.denominator - 1) < f.numerator
if isinstance(f, Real):
return 1 if realIsLess(RandUniform(), f) else 0
return 1 if realIsLess(RandUniform(), RealFraction(f)) else 0
def tulap(m, b, q):
# Tulap(m, b, q). ("truncated uniform Laplace"), m real, b in (0, 1), q in [0, 1).
# Discrete Laplace(b) is Tulap(0,b,0) rounded to nearest integer.
# Awan, Jordan, and Aleksandra Slavković. "Differentially private inference for binomial data." arXiv:1904.00459 (2019).
# Awan, Jordan, and Salil Vadhan. "Canonical Noise Distributions and Private Hypothesis Tests." arXiv preprint arXiv:2108.04303 (2021/2022).
b = RealAdd(b, 0)
q_is_zero = q == 0
q = RealAdd(q, 0)
while True:
g1 = 0
while randBernoulli(b) == 1:
g1 += 1
g2 = 0
while randBernoulli(b) == 1:
g2 += 1
nint = g1 - g2
# Add a random uniform variate in (-1/2, 1/2)
nreal = nint + (RandUniform() - Fraction(1, 2))
if q_is_zero:
# No truncation necessary
return nreal + m
# Truncate between two quantiles. Since
# Tulap(m,b,0) = m + Tulap(0,b,0), just assume
# m=0 in the truncation check.
if realIsLess(nreal, 0):
fn = (1 / (b**nint * (1 + b))) * (
b + (nreal - nint + Fraction(1, 2)) * (1 - b)
)
else:
fn = 1 - (b**nint / (1 + b)) * (
b + (nint - nreal + Fraction(1, 2)) * (1 - b)
)
# if fn < 0 or fn > 1: raise ValueError
if realIsLess(q / 2, fn) and realIsLess(fn, 1 - q / 2):
return nreal + m
def gen_to_transition(s):
size = len(s)
m = [[0 for i in range(size + 1)] for j in range(size)]
for i in range(size):
isum = sum(s[i])
if isum < 0:
m[i][size] = isum / s[i][i]
for j in range(size):
if j != i:
m[i][j] = -s[i][j] / s[i][i]
return m
class PhaseType:
# Samples from a continuous phase-type distribution.
# N is the number of states (other than the
# "absorbing" or terminating state).
# alpha - Probabilities to start in each state. N items.
# s - Sub-generator matrix. List of N lists with N items each.
def __init__(self, alpha, s):
self.n = len(s)
self.alpha = alpha
self.trans = gen_to_transition(s)
# NOTE: Diagonal elements of 's' must each be 0 or less.
self.rates = [-s[i][i] for i in range(len(s))]
def sample(self):
state = random.choices(range(self.n), weights=self.alpha)[0]
ret = RealFraction(0)
while state < self.n:
ret -= RealLn(RandUniform()) / self.rates[state]
state = random.choices(range(self.n + 1), weights=self.trans[state])[0]
return ret
def exchangeable_bernoulli(p, d, lamda=None):
# p=expected value (in [0, 1]); d=dimension; lamda=weights for
# each ray density
# Fontana, Roberto, and Patrizia Semeraro.
# "Exchangeable Bernoulli distributions: high dimensional
# simulation, estimate and testing." arXiv preprint
# arXiv:2101.07693 (2021).
if d <= 0 or int(d) != d:
raise ValueError
if p < 0 or p > 1:
raise ValueError
pd_is_integer = p * d == floor(p * d)
floorpd = p * d - 1 if pd_is_integer else int(p * d)
ceilpd = p * d + 1 if pd_is_integer else int(p * d) + 1
j1count = floorpd + 1
j2count = (d - ceilpd) + 1
densitycount = j1count * j2count
if pd_is_integer:
densitycount += 1
if lamda == None:
# Uniform selection of ray density
rj = random.randint(0, densitycount - 1)
else:
rj = random.choices([i for i in range(len(lamda))], weights=lamda)[0]
# print([j1count,j2count])
jstar = None
if pd_is_integer and rj == densitycount - 1:
jstar = int(p * d)
else:
if rj < 0 or j1count < 0:
raise ValueError
j1 = rj % j1count
j2 = ceilpd + rj // j1count
# print([j1,j2, "---",(j2-p*d)/(j2-j1),(p*d-j1)/(j2-j1)])
jstar = random.choices([j1, j2], weights=[j2 - p * d, p * d - j1])[0]
ret = [1 if i < jstar else 0 for i in range(d)]
if jstar > 0 and jstar < d:
random.shuffle(ret)
return ret
###################
def psrn_complement(x):
# NOTE: Assumes digits is 2
for i in range(len(x[2])):
if x[2][i] != None:
x[2][i] = 1 - x[2][i]
return x
def psrn_new_01():
return [1, 0, []]
def psrn_fill(rg, psrn, precision=53, digits=2):
af = 0
afrac = psrn[2]
asign = psrn[0]
aint = psrn[1]
if asign != -1 and asign != 1:
raise ValueError
hasNoneDigits = False
for d in afrac:
if d == None:
hasNoneDigits = True
if (not hasNoneDigits) and digits == 2:
diglen = (precision + 1) - len(afrac)
if diglen > 0:
rest = rg.rndint((1 << diglen) - 1)
for i in range(diglen):
afrac.append(rest & 1)
rest >>= 1
for i in range(precision + 1):
af = af * digits + afrac[i]
else:
for i in range(precision + 1):
if i >= len(afrac):
afrac.append(rg.rndint(digits - 1))
if afrac[i] == None:
afrac[i] = rg.rndint(digits - 1)
af = af * digits + afrac[i]
if af % digits >= digits - digits // 2:
# round up
return (
asign
* (((af // digits) + 1) + (aint * digits**precision))
/ (digits**precision)
)
else:
return (
asign * ((af // digits) + (aint * digits**precision)) / (digits**precision)
)
def psrn_in_range(rg, bmin, bmax, digits=2):
if bmin >= bmax:
raise ValueError
if bmin >= 0 and bmax >= 0:
return psrn_in_range_positive(rg, bmin, bmax, digits)
if bmin <= 0 and bmax <= 0:
ret = psrn_in_range_positive(rg, abs(bmax), abs(bmin), digits)
ret[0] = -1
return ret
while True:
a = psrn_new_01()
bmaxi = int(bmax)
if bmax < 0 and bmax != bmaxi:
bmaxi -= 1
bmini = int(bmin)
if bmin < 0 and bmin != bmini:
bmini -= 1
ipart = (
bmini + rg.rndint(bmaxi - 1 - bmini)
if bmaxi == bmax
else bmini + rg.rndint(bmaxi - bmini)
)
if ipart != bmini and ipart != bmaxi:
a[0] = 1 if ipart >= 0 else -1
a[1] = abs(ipart + 1) if ipart < 0 else ipart
return a
if ipart == bmini:
a[0] = 1
a[1] = abs(ipart + 1)
if psrn_less_than_fraction(rg, a, abs(bmin), digits) == 1:
a[0] = -1
return a
if ipart == bmaxi:
a[0] = 1
a[1] = ipart
if psrn_less_than_fraction(rg, a, bmax, digits) == 1:
a[0] = 1
return a
def psrn_in_range_positive(rg, bmin, bmax, digits=2):
if bmin >= bmax or bmin < 0 or bmax <= 0:
raise ValueError
a = psrn_new_01()
if bmax == 1 and bmin == 0:
return a
bmaxi = int(bmax)
bmini = int(bmin)
if bmini == bmin and bmaxi == bmax:
a[0] = 1
a[1] = bmini + rg.rndint(bmaxi - 1 - bmini)
return a
# count = 0
while True:
# count += 1
# if count>=20 and count%10==0:
# print([count,float(bmin),float(bmax)])
a[0] = 1
if bmaxi == bmax:
a[1] = bmini + rg.rndint(bmaxi - 1 - bmini)
else:
a[1] = bmini + rg.rndint(bmaxi - bmini)
# print([a[1],"bmini",bmini,float(bmin),"bmaxi",bmaxi,float(bmax)])
if a[1] > bmini and a[1] < bmaxi:
return a
if bmin == bmini and a[1] == bmini and a[1] < bmaxi:
return a
bmaxv = bmax - bmaxi
bminv = bmin - bmini
if a[1] != bmini and a[1] != bmaxi:
raise ValueError
i = 0
istart = 0
if a[1] == bmini and a[1] == bmaxi:
while True:
dmin = int(digits * bminv)
dmax = int(digits * bmaxv)
if dmin != dmax:
break
a[2].append(dmin)
bminv = bminv * digits - dmin
bmaxv = bmaxv * digits - dmax
i += 1
istart = i
i = istart
if a[1] == bmini:
success = 0
while True:
bminv *= digits
dmin = int(bminv)
bminv -= dmin
if i >= len(a[2]):
a[2].append(None)
if a[2][i] == None:
a[2][i] = rg.rndint(digits - 1)
ad = a[2][i]
# print([i,"=bmini<bmaxi",dmin,ad,a,float(bminv),"bmini",a[1]])
if ad > dmin:
success = 1
break
if ad < dmin:
a = psrn_new_01()
break
i += 1
if not success:
continue
i = istart
if a[1] == bmaxi:
success = 0
if bmaxi == 0 and bmaxi != bmax and len(a[2]) == 0:
while True:
d = int(bmaxv * digits)
if d != 0:
break
bmaxv *= digits
bmaxv -= d
a[2].append(0)
i += 1
while True:
bmaxv *= digits
dmax = int(bmaxv)
bmaxv -= dmax
if i >= len(a[2]):
a[2].append(None)
if a[2][i] == None:
a[2][i] = rg.rndint(digits - 1)
ad = a[2][i]
# print([i,"=bmaxi>bmini",dmax,ad,a,"bmaxi",a[1]])
if ad < dmax:
success = 1
break
if ad > dmax or bmaxv == 0:
a = psrn_new_01()
break
i += 1
if not success:
continue
return a
def psrn_sample(rg, psrn, digits=2):
return psrn_less(rg, psrn_new_01(), [1, 0, psrn[2]], digits)
def psrn_less(rg, psrn1, psrn2, digits=2):
if psrn1[0] == None or psrn1[1] == None or psrn2[0] == None or psrn2[1] == None:
raise ValueError
if psrn1[0] != psrn2[0]:
return 1 if psrn1[0] < 0 else 0
if psrn1[0] >= 0:
if psrn1[1] < psrn2[1]:
return 1
if psrn1[1] > psrn2[1]:
return 0
if psrn1[0] < 0:
if psrn1[1] < psrn2[1]:
return 0
if psrn1[1] > psrn2[1]:
return 1
index = 0
psrn1len = len(psrn1[2])
psrn2len = len(psrn2[2])
while True:
# Fill with next digit in a's uniform number
while psrn1len <= index:
psrn1[2].append(rg.rndint(digits - 1))
psrn1len += 1
if psrn1[2][index] == None:
psrn1[2][index] = rg.rndint(digits - 1)
# Fill with next digit in b's uniform number
while psrn2len <= index:
psrn2[2].append(rg.rndint(digits - 1))
psrn2len += 1
if psrn2[2][index] == None:
psrn2[2][index] = rg.rndint(digits - 1)
aa = psrn1[2][index]
bb = psrn2[2][index]
if aa < bb:
return 1
if aa > bb:
return 0
index += 1
def psrn_less_than_fraction(rg, psrn, rat, digits=2):
if (psrn[0] != -1 and psrn[0] != 1) or psrn[1] == None:
raise ValueError
rat = rat if isinstance(rat, Fraction) else Fraction(rat)
num = rat.numerator
den = rat.denominator
if num < 0 and den < 0:
num = abs(num)
den = abs(den)
bs = -1 if num < 0 or den < 0 else 1
num = abs(num)
den = abs(den)
bi = int(num // den)
num = num - den * bi
sgn = 0
if psrn[0] < 0:
sgn = -1
if psrn[0] > 0:
sgn = 1
if sgn != bs:
return 1 if psrn[0] < 0 else 0
if psrn[0] > 0:
if psrn[1] < bi:
return 1
if psrn[1] > bi:
return 0
if psrn[0] < 0:
if psrn[1] > bi:
return 1
if psrn[1] < bi:
return 0
if den == 0:
raise ValueError
if num == 0:
# Is an integer
return 0 if psrn[0] > 0 else 1
pt = digits
index = 0
psrnlen = len(psrn[2])
while True:
# Fill with next digit in a's uniform number
while psrnlen <= index:
psrn[2].append(rg.rndint(digits - 1))
psrnlen += 1
if psrn[2][index] == None:
psrn[2][index] = rg.rndint(digits - 1)
d1 = psrn[2][index]
c = 1 if num * pt >= den else 0
d2 = (num * pt) // den
if d2 < 0 or d2 >= digits:
raise ValueError
if d1 < d2:
return 1 if psrn[0] > 0 else 0
if d1 > d2:
return 0 if psrn[0] > 0 else 1
if c == 1:
num = num * pt - den * d2
den = den * pt
if num == 0:
return 0 if psrn[0] > 0 else 1
pt *= digits
index += 1
def psrn_reciprocal(rg, psrn1, digits=2):
"""Generates the reciprocal of a partially-sampled random number.
psrn1: List containing the sign, integer part, and fractional part
of the first PSRN. Fractional part is a list of digits
after the point, starting with the first.
digits: Digit base of PSRNs' digits. Default is 2, or binary."""
if psrn1[0] == None or psrn1[1] == None:
raise ValueError
for i in range(len(psrn1[2])):
psrn1[2][i] = rg.rndint(digits - 1) if psrn1[2][i] == None else psrn1[2][i]
digitcount = len(psrn1[2])
frac1 = psrn1[1]
for i in range(digitcount):
frac1 = frac1 * digits + psrn1[2][i]
while frac1 == 0:
# Avoid degenerate cases
d1 = rg.rndint(digits - 1)
psrn1[2].append(d1)
frac1 = frac1 * digits + d1
digitcount += 1
while True:
dcount = digitcount
ddc = digits**dcount
small = Fraction(ddc, frac1 + 1)
large = Fraction(ddc, frac1)
if small > large:
raise ValueError
if small == 0:
raise ValueError
while True:
dc = int(small * ddc)
if dc != 0:
break
dcount += 1
ddc *= digits
dc2 = int(large * ddc) + 1
rv = dc + rg.rndint(dc2 - 1 - dc)
rvx = rg.rndint(dc - 1)
# print([count,float(small), float(large),dcount, dc/ddc, dc2/ddc])
while True:
rvsmall = Fraction(rv, ddc)
rvlarge = Fraction(rv + 1, ddc)
if rvsmall >= small and rvlarge < large:
rvd = Fraction(dc, ddc)
rvxf = Fraction(rvx, dc)
rvxf2 = Fraction(rvx + 1, dc)
# print(["dcs",rvx,"rvsmall",float(rvsmall),"rvlarge",float(rvlarge),"small",float(small),
# "rvxf",float(rvxf),float(rvxf2),"rvd",float(rvd),
# "sl",float((rvd*rvd)/(rvlarge*rvlarge)),float((rvd*rvd)/(rvsmall*rvsmall))])
if rvxf2 < (rvd * rvd) / (rvlarge * rvlarge):
cpsrn = [1, 0, [0 for i in range(dcount)]]
cpsrn[0] = psrn1[0]
sret = rv
for i in range(dcount):
cpsrn[2][dcount - 1 - i] = sret % digits
sret //= digits
cpsrn[1] = sret
return cpsrn
elif rvxf > (rvd * rvd) / (rvsmall * rvsmall):
break
elif rvsmall > large or rvlarge < small:
break
rv = rv * digits + rg.rndint(digits - 1)
rvx = rvx * digits + rg.rndint(digits - 1)
dcount += 1
ddc *= digits
dc *= digits
def proddist(x, a, b, c, d):
if a * d < b * c:
aa = a
bb = b
cc = c
dd = d
a = cc
b = dd
c = aa
d = bb
if a * c > x:
x = a * c
if b * d < x:
x = b * d
if a * c <= x and x <= b * c:
r = max(0, min(1, math.log(x / (a * c)))) / math.log(b / a)
elif b * c <= x and x <= a * d:
r = 1
else:
r = max(0, min(1, math.log(b * d / x))) / math.log(b / a)
return max(0, min(1, r))
def proddist2(x, a, b, c, d):
if a * d < b * c:
aa = a
bb = b
cc = c
dd = d
a = cc
b = dd
c = aa
d = bb
if a * c > x:
x = a * c
if b * d < x:
x = b * d
if a * c <= x and x <= b * c:
r = [Fraction(x, a * c), Fraction(b, a)]
elif b * c <= x and x <= a * d:
r = [Fraction(b, a), Fraction(b, a)]
else:
r = [Fraction(b * d, x), Fraction(b, a)]
return r
def psrn_multiply(rg, psrn1, psrn2, digits=2):
"""Multiplies two uniform partially-sampled random numbers.
psrn1: List containing the sign, integer part, and fractional part
of the first PSRN. Fractional part is a list of digits
after the point, starting with the first.
psrn2: List containing the sign, integer part, and fractional part
of the second PSRN.
digits: Digit base of PSRNs' digits. Default is 2, or binary."""
return psrn_multiply_b(rg, psrn1, psrn2, digits=digits)
def _dlc(rg, psrn, c, digits=2):
i = rg.rndint(c - 1)
if i < psrn[1]:
return 1
if i == psrn[1]:
return psrn_sample(rg, psrn, digits=digits)
return 0
def _log_1n(rg, c):
# ln(1+1/c)
u = None
while True:
if rg.rndint(1) == 0:
return 1 if rg.rndint(c - 1) == 0 else 0
if u == None:
u = psrn_new_01()
if psrn_sample(rg, u) == 1:
if rg.rndint(c - 1) == 0:
return 0
def _log_yxyz(rg, psrn, st, digits=2):
# ln((st+psrn)/st)
if psrn[0] < 0 or psrn[1] > st:
raise ValueError([psrn[1], "st", st])
u = None
while True:
if rg.rndint(1) == 0:
return _dlc(rg, psrn, st, digits=digits)
if u == None:
u = psrn_new_01()
if psrn_sample(rg, u, digits=digits) == 1:
if _dlc(rg, psrn, st, digits=digits) == 1:
return 0
def _dlc2(rg, psrn, n, d, digits=2):
while True:
if rg.rndint(d) != d:
i = rg.rndint(d - 1)
if i < n:
return 1
if i == n:
return 1 - psrn_sample(rg, psrn, digits=digits)
return 0
if psrn_sample(rg, psrn, digits=digits) == 1:
return 0
def _log_xyzy(rg, psrn, large, midmax, digits=2):
# ln(large/(midmax+psrn))
if psrn[0] < 0:
raise ValueError
u = None
n = large - psrn[1] - midmax - 1
d = psrn[1] + midmax
while True:
if rg.rndint(1) == 0:
return _dlc2(rg, psrn, n, d, digits=digits)
if u == None:
u = psrn_new_01()
if psrn_sample(rg, u, digits=digits) == 1:
if _dlc2(rg, psrn, n, d, digits=digits) == 1:
return 0
def _log_yxyz_test(ps, st):
import scipy.integrate as spi
rg = bernoulli.Bernoulli()
print(spi.quad(lambda x: math.log((st + ps + x) / st), 0, 1)[0])
print(sum(_log_yxyz(rg, [1, ps, []], st) for i in range(100000)) / 100000)
def _log_xyzy_test(ps, large, midmax):
import scipy.integrate as spi
rg = bernoulli.Bernoulli()
print(spi.quad(lambda x: math.log(large / (midmax + ps + x)), 0, 1)[0])
print(
sum(_log_xyzy(rg, [1, ps, []], large, midmax) for i in range(100000)) / 100000
)
def _dlc2_test(n, d):
import scipy.integrate as spi
rg = bernoulli.Bernoulli()
print(spi.quad(lambda x: (n + (1 - x)) / (d + x), 0, 1)[0])
print(sum(_dlc2(rg, [1, 0, []], n, d) for i in range(100000)) / 100000)
if False:
_dlc2_test(0, 19)
_dlc2_test(12, 19)
_dlc2_test(17, 19)
_log_yxyz_test(0, 1)
_log_yxyz_test(0, 2)
_log_yxyz_test(0, 50)
_log_yxyz_test(3, 50)
_log_yxyz_test(7, 50)
_log_yxyz_test(20, 50)
_log_xyzy_test(3, 20, 16)
_log_xyzy_test(1, 32, 30)
_log_xyzy_test(0, 16, 14)
exit()
def psrn_multiply_b(rg, psrn1, psrn2, digits=2, testing=False):
if psrn1[0] == None or psrn1[1] == None or psrn2[0] == None or psrn2[1] == None:
raise ValueError
for i in range(len(psrn1[2])):
psrn1[2][i] = rg.rndint(digits - 1) if psrn1[2][i] == None else psrn1[2][i]
for i in range(len(psrn2[2])):
psrn2[2][i] = rg.rndint(digits - 1) if psrn2[2][i] == None else psrn2[2][i]
while len(psrn1[2]) < len(psrn2[2]):
psrn1[2].append(rg.rndint(digits - 1))
while len(psrn1[2]) > len(psrn2[2]):
psrn2[2].append(rg.rndint(digits - 1))
digitcount = len(psrn1[2])
if len(psrn2[2]) != digitcount:
raise ValueError
# Perform multiplication
frac1 = psrn1[1]
frac2 = psrn2[1]
for i in range(digitcount):
frac1 = frac1 * digits + psrn1[2][i]
for i in range(digitcount):
frac2 = frac2 * digits + psrn2[2][i]
zero = False # (frac1 == 0 and frac2 != 0) or (frac2 == 0 and frac1 != 0)
# print(["before",frac1,frac2,zero])
while frac1 == 0 or frac2 == 0:
# Avoid degenerate cases
d1 = rg.rndint(digits - 1)
psrn1[2].append(d1)
d2 = rg.rndint(digits - 1)
psrn2[2].append(d2)
frac1 = frac1 * digits + d1
frac2 = frac2 * digits + d2
digitcount += 1
# print(["after",frac1,frac2])
small = frac1 * frac2
mid1 = frac1 * (frac2 + 1)
mid2 = (frac1 + 1) * frac2
large = (frac1 + 1) * (frac2 + 1)
midmin = min(mid1, mid2)
midmax = max(mid1, mid2)
dc2 = digitcount * 2
cpsrn = [1, 0, [0 for i in range(dc2)]]
cpsrn[0] = psrn1[0] * psrn2[0]
iters = 0
while True:
iters += 1
if iters > 1500:
return None
rv = rg.rndint(large - small - 1)
if (not zero) and (rv < midmin - small or rv >= midmax - small):
ru = small + rv
succ = False
if rv < midmin - small:
psrn = [1, ru - small, []] # PSRN
succ = _log_yxyz(rg, psrn, small, digits=digits) == 1
else:
psrn = [1, ru - midmax, []] # PSRN
succ = _log_xyzy(rg, psrn, large, midmax, digits=digits) == 1
if succ:
# Success
sret = ru
for i in range(dc2):
idx = (dc2) - 1 - i
while idx >= len(cpsrn[2]):
cpsrn[2].append(None)
cpsrn[2][idx] = sret % digits
sret //= digits
for i in range(len(psrn[2])):
idx = dc2 + i
while idx >= len(cpsrn[2]):
cpsrn[2].append(None)
cpsrn[2][idx] = psrn[2][i]
cpsrn[1] = sret
# if iters>100:print(iters)
return cpsrn
else:
# Middle, or uniform, part of product density
if not zero:
if mid1 > mid2:
if _log_1n(rg, frac1) == 0:
continue
else:
if _log_1n(rg, frac2) == 0:
continue
sret = small + rv
for i in range(dc2):
cpsrn[2][dc2 - 1 - i] = sret % digits
sret //= digits
cpsrn[1] = sret
# if iters>100:print(iters)
return cpsrn
def psrn_multiply_by_fraction(rg, psrn1, fraction, digits=2):
"""Multiplies a partially-sampled random number by a fraction.
psrn1: List containing the sign, integer part, and fractional part
of the first PSRN. Fractional part is a list of digits
after the point, starting with the first.
fraction: Fraction to multiply by.
digits: Digit base of PSRNs' digits. Default is 2, or binary."""
if psrn1[0] == None or psrn1[1] == None:
raise ValueError
fraction = Fraction(fraction)
for i in range(len(psrn1[2])):
psrn1[2][i] = rg.rndint(digits - 1) if psrn1[2][i] == None else psrn1[2][i]
digitcount = len(psrn1[2])
# Perform multiplication
frac1 = psrn1[1]
fracsign = -1 if fraction < 0 else 1
absfrac = abs(fraction)
for i in range(digitcount):
frac1 = frac1 * digits + psrn1[2][i]
while True:
dcount = digitcount
ddc = digits**dcount
small = Fraction(frac1, ddc) * absfrac
large = Fraction(frac1 + 1, ddc) * absfrac
dc = int(small * ddc)
dc2 = int(large * ddc) + 1
rv = dc + rg.rndint(dc2 - 1 - dc)
while True:
rvsmall = Fraction(rv, ddc)
rvlarge = Fraction(rv + 1, ddc)
if rvsmall >= small and rvlarge < large:
cpsrn = [1, 0, [0 for i in range(dcount)]]
cpsrn[0] = psrn1[0] * fracsign
sret = rv
for i in range(dcount):
cpsrn[2][dcount - 1 - i] = sret % digits
sret //= digits
cpsrn[1] = sret
return cpsrn
elif rvsmall > large or rvlarge < small:
break
else:
rv = rv * digits + rg.rndint(digits - 1)
dcount += 1
ddc *= digits
def psrn_add(rg, psrn1, psrn2, digits=2):
"""Adds two uniform partially-sampled random numbers.
psrn1: List containing the sign, integer part, and fractional part
of the first PSRN. Fractional part is a list of digits
after the point, starting with the first.
psrn2: List containing the sign, integer part, and fractional part
of the second PSRN.
digits: Digit base of PSRNs' digits. Default is 2, or binary."""
if psrn1[0] == None or psrn1[1] == None or psrn2[0] == None or psrn2[1] == None:
raise ValueError
for i in range(len(psrn1[2])):
psrn1[2][i] = rg.rndint(digits - 1) if psrn1[2][i] == None else psrn1[2][i]
for i in range(len(psrn2[2])):
psrn2[2][i] = rg.rndint(digits - 1) if psrn2[2][i] == None else psrn2[2][i]
while len(psrn1[2]) < len(psrn2[2]):
psrn1[2].append(rg.rndint(digits - 1))
while len(psrn1[2]) > len(psrn2[2]):
psrn2[2].append(rg.rndint(digits - 1))
digitcount = len(psrn1[2])
if len(psrn2[2]) != digitcount:
raise ValueError
# Perform addition
frac1 = psrn1[1]
frac2 = psrn2[1]
for i in range(digitcount):
frac1 = frac1 * digits + psrn1[2][i]
for i in range(digitcount):
frac2 = frac2 * digits + psrn2[2][i]
small = frac1 * psrn1[0] + frac2 * psrn2[0]
mid1 = frac1 * psrn1[0] + (frac2 + 1) * psrn2[0]
mid2 = (frac1 + 1) * psrn1[0] + frac2 * psrn2[0]
large = (frac1 + 1) * psrn1[0] + (frac2 + 1) * psrn2[0]
minv = min(small, mid1, mid2, large)
maxv = max(small, mid1, mid2, large)
# Difference is expected to be a multiple of two
if abs(maxv - minv) % 2 != 0:
raise ValueError
vs = [small, mid1, mid2, large]
vs.sort()
midmin = vs[1]
midmax = vs[2]
while True:
rv = rg.rndint(maxv - minv - 1)
if rv < 0:
raise ValueError
side = 0
start = minv
if rv < midmin - minv:
# Left side of sum density; rising triangular
side = 0
start = minv
elif rv >= midmax - minv:
# Right side of sum density; falling triangular
side = 1
start = midmax
else:
# Middle, or uniform, part of sum density
sret = minv + rv
cpsrn = [1, 0, [0 for i in range(digitcount)]]
if sret < 0:
sret += 1
cpsrn[0] = -1
sret = abs(sret)
for i in range(digitcount):
cpsrn[2][digitcount - 1 - i] = sret % digits
sret //= digits
cpsrn[1] = sret
return cpsrn
if side == 0: # Left side
pw = rv
b = midmin - minv
else:
pw = rv - (midmax - minv)
b = maxv - midmax
newdigits = 0
y = rg.rndint(b - 1)
while True:
lowerbound = pw if side == 0 else b - 1 - pw
if y < lowerbound:
# Success
sret = start * (digits**newdigits) + pw
cpsrn = [1, 0, [0 for i in range(digitcount + newdigits)]]
if sret < 0:
sret += 1
cpsrn[0] = -1
sret = abs(sret)
for i in range(digitcount + newdigits):
idx = (digitcount + newdigits) - 1 - i
while idx >= len(cpsrn[2]):
cpsrn[2].append(None)
cpsrn[2][idx] = sret % digits
sret //= digits
cpsrn[1] = sret
return cpsrn
elif y > lowerbound + 1: # Greater than upper bound
# Rejected
break
pw = pw * digits + rg.rndint(digits - 1)
y = y * digits + rg.rndint(digits - 1)
b *= digits
newdigits += 1
def psrn_add_fraction(rg, psrn, fraction, digits=2):
if psrn[0] == None or psrn[1] == None:
raise ValueError
fraction = Fraction(fraction)
fracsign = -1 if fraction < 0 else 1
absfrac = abs(fraction)
origfrac = fraction
isinteger = absfrac.denominator == 1