-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathrandomimpl.py
2336 lines (1932 loc) · 79.7 KB
/
randomimpl.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
"""
Implement the random and np.random module functions.
"""
import math
import random
import numpy as np
from llvmlite import ir
from numba.core.cgutils import is_nonelike, is_empty_tuple
from numba.core.extending import intrinsic, overload, register_jitable
from numba.core.imputils import (Registry, impl_ret_untracked,
impl_ret_new_ref)
from numba.core.typing import signature
from numba.core import types, cgutils
from numba.core.errors import NumbaTypeError
from numba.np.random._constants import LONG_MAX
registry = Registry('randomimpl')
lower = registry.lower
int32_t = ir.IntType(32)
int64_t = ir.IntType(64)
def const_int(x):
return ir.Constant(int32_t, x)
double = ir.DoubleType()
N = 624
N_const = ir.Constant(int32_t, N)
# This is the same struct as rnd_state_t in _random.c.
rnd_state_t = ir.LiteralStructType([
# index
int32_t,
# mt[N]
ir.ArrayType(int32_t, N),
# has_gauss
int32_t,
# gauss
double,
# is_initialized
int32_t,
])
rnd_state_ptr_t = ir.PointerType(rnd_state_t)
def get_state_ptr(context, builder, name):
"""
Get a pointer to the given thread-local random state
(depending on *name*: "py" or "np").
If the state isn't initialized, it is lazily initialized with
system entropy.
"""
assert name in ('py', 'np', 'internal')
func_name = "numba_get_%s_random_state" % name
fnty = ir.FunctionType(rnd_state_ptr_t, ())
fn = cgutils.get_or_insert_function(builder.module, fnty, func_name)
# These two attributes allow LLVM to hoist the function call
# outside of loops.
fn.attributes.add('readnone')
fn.attributes.add('nounwind')
return builder.call(fn, ())
def get_py_state_ptr(context, builder):
"""
Get a pointer to the thread-local Python random state.
"""
return get_state_ptr(context, builder, 'py')
def get_np_state_ptr(context, builder):
"""
Get a pointer to the thread-local Numpy random state.
"""
return get_state_ptr(context, builder, 'np')
def get_internal_state_ptr(context, builder):
"""
Get a pointer to the thread-local internal random state.
"""
return get_state_ptr(context, builder, 'internal')
# Accessors
def get_index_ptr(builder, state_ptr):
return cgutils.gep_inbounds(builder, state_ptr, 0, 0)
def get_array_ptr(builder, state_ptr):
return cgutils.gep_inbounds(builder, state_ptr, 0, 1)
def get_has_gauss_ptr(builder, state_ptr):
return cgutils.gep_inbounds(builder, state_ptr, 0, 2)
def get_gauss_ptr(builder, state_ptr):
return cgutils.gep_inbounds(builder, state_ptr, 0, 3)
def get_rnd_shuffle(builder):
"""
Get the internal function to shuffle the MT taste.
"""
fnty = ir.FunctionType(ir.VoidType(), (rnd_state_ptr_t,))
fn = cgutils.get_or_insert_function(builder.function.module, fnty,
"numba_rnd_shuffle")
fn.args[0].add_attribute("nocapture")
return fn
def get_next_int32(context, builder, state_ptr):
"""
Get the next int32 generated by the PRNG at *state_ptr*.
"""
idxptr = get_index_ptr(builder, state_ptr)
idx = builder.load(idxptr)
need_reshuffle = builder.icmp_unsigned('>=', idx, N_const)
with cgutils.if_unlikely(builder, need_reshuffle):
fn = get_rnd_shuffle(builder)
builder.call(fn, (state_ptr,))
builder.store(const_int(0), idxptr)
idx = builder.load(idxptr)
array_ptr = get_array_ptr(builder, state_ptr)
y = builder.load(cgutils.gep_inbounds(builder, array_ptr, 0, idx))
idx = builder.add(idx, const_int(1))
builder.store(idx, idxptr)
# Tempering
y = builder.xor(y, builder.lshr(y, const_int(11)))
y = builder.xor(y, builder.and_(builder.shl(y, const_int(7)),
const_int(0x9d2c5680)))
y = builder.xor(y, builder.and_(builder.shl(y, const_int(15)),
const_int(0xefc60000)))
y = builder.xor(y, builder.lshr(y, const_int(18)))
return y
def get_next_double(context, builder, state_ptr):
"""
Get the next double generated by the PRNG at *state_ptr*.
"""
# a = rk_random(state) >> 5, b = rk_random(state) >> 6;
a = builder.lshr(get_next_int32(context, builder, state_ptr), const_int(5))
b = builder.lshr(get_next_int32(context, builder, state_ptr), const_int(6))
# return (a * 67108864.0 + b) / 9007199254740992.0;
a = builder.uitofp(a, double)
b = builder.uitofp(b, double)
return builder.fdiv(
builder.fadd(b, builder.fmul(a, ir.Constant(double, 67108864.0))),
ir.Constant(double, 9007199254740992.0))
def get_next_int(context, builder, state_ptr, nbits, is_numpy):
"""
Get the next integer with width *nbits*.
"""
c32 = ir.Constant(nbits.type, 32)
def get_shifted_int(nbits):
shift = builder.sub(c32, nbits)
y = get_next_int32(context, builder, state_ptr)
# This truncation/extension is safe because 0 < nbits <= 64
if nbits.type.width < y.type.width:
shift = builder.zext(shift, y.type)
elif nbits.type.width > y.type.width:
shift = builder.trunc(shift, y.type)
if is_numpy:
# Use the last N bits, to match np.random
mask = builder.not_(ir.Constant(y.type, 0))
mask = builder.lshr(mask, shift)
return builder.and_(y, mask)
else:
# Use the first N bits, to match CPython random
return builder.lshr(y, shift)
ret = cgutils.alloca_once_value(builder, ir.Constant(int64_t, 0))
is_32b = builder.icmp_unsigned('<=', nbits, c32)
with builder.if_else(is_32b) as (ifsmall, iflarge):
with ifsmall:
low = get_shifted_int(nbits)
builder.store(builder.zext(low, int64_t), ret)
with iflarge:
# XXX This assumes nbits <= 64
if is_numpy:
# Get the high bits first to match np.random
high = get_shifted_int(builder.sub(nbits, c32))
low = get_next_int32(context, builder, state_ptr)
if not is_numpy:
# Get the high bits second to match CPython random
high = get_shifted_int(builder.sub(nbits, c32))
total = builder.add(
builder.zext(low, int64_t),
builder.shl(builder.zext(high, int64_t),
ir.Constant(int64_t, 32)))
builder.store(total, ret)
return builder.load(ret)
@overload(random.seed)
def seed_impl(a):
if isinstance(a, types.Integer):
fn = register_jitable(_seed_impl('py'))
def impl(a):
return fn(a)
return impl
@overload(np.random.seed)
def seed_impl(seed):
if isinstance(seed, types.Integer):
return _seed_impl('np')
def _seed_impl(state_type):
@intrinsic
def _impl(typingcontext, seed):
def codegen(context, builder, sig, args):
seed_value, = args
fnty = ir.FunctionType(ir.VoidType(), (rnd_state_ptr_t, int32_t))
fn = cgutils.get_or_insert_function(builder.function.module, fnty,
'numba_rnd_init')
builder.call(fn, (get_state_ptr(context, builder, state_type),
seed_value))
return context.get_constant(types.none, None)
return signature(types.void, types.uint32), codegen
return lambda seed: _impl(seed)
@overload(random.random)
def random_impl():
@intrinsic
def _impl(typingcontext):
def codegen(context, builder, sig, args):
state_ptr = get_state_ptr(context, builder, "py")
return get_next_double(context, builder, state_ptr)
return signature(types.double), codegen
return lambda: _impl()
@overload(np.random.random)
@overload(np.random.random_sample)
@overload(np.random.sample)
@overload(np.random.ranf)
def random_impl0():
@intrinsic
def _impl(typingcontext):
def codegen(context, builder, sig, args):
state_ptr = get_state_ptr(context, builder, "np")
return get_next_double(context, builder, state_ptr)
return signature(types.float64), codegen
return lambda: _impl()
@overload(np.random.random)
@overload(np.random.random_sample)
@overload(np.random.sample)
@overload(np.random.ranf)
def random_impl1(size=None):
if is_nonelike(size):
return lambda size=None: np.random.random()
if is_empty_tuple(size):
# Handle size = ()
return lambda size=None: np.array(np.random.random())
if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple)
and isinstance(size.dtype,
types.Integer)):
def _impl(size=None):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.random()
return out
return _impl
@overload(random.gauss)
@overload(random.normalvariate)
def gauss_impl(mu, sigma):
if isinstance(mu, (types.Float, types.Integer)) and isinstance(
sigma, (types.Float, types.Integer)):
@intrinsic
def _impl(typingcontext, mu, sigma):
loc_preprocessor = _double_preprocessor(mu)
scale_preprocessor = _double_preprocessor(sigma)
return signature(types.float64, mu, sigma),\
_gauss_impl("py", loc_preprocessor, scale_preprocessor)
return lambda mu, sigma: _impl(mu, sigma)
@overload(np.random.standard_normal)
@overload(np.random.normal)
def np_gauss_impl0():
return lambda: np.random.normal(0.0, 1.0)
@overload(np.random.normal)
def np_gauss_impl1(loc):
if isinstance(loc, (types.Float, types.Integer)):
return lambda loc: np.random.normal(loc, 1.0)
@overload(np.random.normal)
def np_gauss_impl2(loc, scale):
if isinstance(loc, (types.Float, types.Integer)) and isinstance(
scale, (types.Float, types.Integer)):
@intrinsic
def _impl(typingcontext, loc, scale):
loc_preprocessor = _double_preprocessor(loc)
scale_preprocessor = _double_preprocessor(scale)
return signature(types.float64, loc, scale),\
_gauss_impl("np", loc_preprocessor, scale_preprocessor)
return lambda loc, scale: _impl(loc, scale)
@overload(np.random.standard_normal)
def standard_normal_impl1(size):
if is_nonelike(size):
return lambda size: np.random.standard_normal()
if is_empty_tuple(size):
# Handle size = ()
return lambda size: np.array(np.random.standard_normal())
if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and
isinstance(size.dtype,
types.Integer)):
def _impl(size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.standard_normal()
return out
return _impl
@overload(np.random.normal)
def np_gauss_impl3(loc, scale, size):
if (isinstance(loc, (types.Float, types.Integer)) and isinstance(
scale, (types.Float, types.Integer)) and
is_nonelike(size)):
return lambda loc, scale, size: np.random.normal(loc, scale)
if (isinstance(loc, (types.Float, types.Integer)) and isinstance(
scale, (types.Float, types.Integer)) and
is_empty_tuple(size)):
# Handle size = ()
return lambda loc, scale, size: np.array(np.random.normal(loc, scale))
if (isinstance(loc, (types.Float, types.Integer)) and isinstance(
scale, (types.Float, types.Integer)) and
(isinstance(size, types.Integer) or (isinstance(size, types.UniTuple)
and isinstance(size.dtype,
types.Integer)))):
def _impl(loc, scale, size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.normal(loc, scale)
return out
return _impl
def _gauss_pair_impl(_random):
def compute_gauss_pair():
"""
Compute a pair of numbers on the normal distribution.
"""
while True:
x1 = 2.0 * _random() - 1.0
x2 = 2.0 * _random() - 1.0
r2 = x1*x1 + x2*x2
if r2 < 1.0 and r2 != 0.0:
break
# Box-Muller transform
f = math.sqrt(-2.0 * math.log(r2) / r2)
return f * x1, f * x2
return compute_gauss_pair
def _gauss_impl(state, loc_preprocessor, scale_preprocessor):
def _impl(context, builder, sig, args):
# The type for all computations (either float or double)
ty = sig.return_type
llty = context.get_data_type(ty)
_random = {"py": random.random,
"np": np.random.random}[state]
state_ptr = get_state_ptr(context, builder, state)
ret = cgutils.alloca_once(builder, llty, name="result")
gauss_ptr = get_gauss_ptr(builder, state_ptr)
has_gauss_ptr = get_has_gauss_ptr(builder, state_ptr)
has_gauss = cgutils.is_true(builder, builder.load(has_gauss_ptr))
with builder.if_else(has_gauss) as (then, otherwise):
with then:
# if has_gauss: return it
builder.store(builder.load(gauss_ptr), ret)
builder.store(const_int(0), has_gauss_ptr)
with otherwise:
# if not has_gauss: compute a pair of numbers using the Box-Muller
# transform; keep one and return the other
pair = context.compile_internal(builder,
_gauss_pair_impl(_random),
signature(types.UniTuple(ty, 2)),
())
first, second = cgutils.unpack_tuple(builder, pair, 2)
builder.store(first, gauss_ptr)
builder.store(second, ret)
builder.store(const_int(1), has_gauss_ptr)
mu, sigma = args
return builder.fadd(loc_preprocessor(builder, mu),
builder.fmul(scale_preprocessor(builder, sigma),
builder.load(ret)))
return _impl
def _double_preprocessor(value):
ty = ir.types.DoubleType()
if isinstance(value, types.Integer):
if value.signed:
return lambda builder, v: builder.sitofp(v, ty)
else:
return lambda builder, v: builder.uitofp(v, ty)
elif isinstance(value, types.Float):
if value.bitwidth != 64:
return lambda builder, v: builder.fpext(v, ty)
else:
return lambda _builder, v: v
else:
raise NumbaTypeError("Cannot convert {} to floating point type" % value)
@overload(random.getrandbits)
def getrandbits_impl(k):
if isinstance(k, types.Integer):
@intrinsic
def _impl(typingcontext, k):
def codegen(context, builder, sig, args):
nbits, = args
too_large = builder.icmp_unsigned(">=", nbits, const_int(65))
too_small = builder.icmp_unsigned("==", nbits, const_int(0))
with cgutils.if_unlikely(builder, builder.or_(too_large,
too_small)):
msg = "getrandbits() limited to 64 bits"
context.call_conv.return_user_exc(builder, OverflowError,
(msg,))
state_ptr = get_state_ptr(context, builder, "py")
return get_next_int(context, builder, state_ptr, nbits, False)
return signature(types.uint64, k), codegen
return lambda k: _impl(k)
def _randrange_impl(context, builder, start, stop, step, ty, signed, state):
state_ptr = get_state_ptr(context, builder, state)
zero = ir.Constant(ty, 0)
one = ir.Constant(ty, 1)
nptr = cgutils.alloca_once(builder, ty, name="n")
# n = stop - start
builder.store(builder.sub(stop, start), nptr)
with builder.if_then(builder.icmp_signed('<', step, zero)):
# n = (n + step + 1) // step
w = builder.add(builder.add(builder.load(nptr), step), one)
n = builder.sdiv(w, step)
builder.store(n, nptr)
with builder.if_then(builder.icmp_signed('>', step, one)):
# n = (n + step - 1) // step
w = builder.sub(builder.add(builder.load(nptr), step), one)
n = builder.sdiv(w, step)
builder.store(n, nptr)
n = builder.load(nptr)
with cgutils.if_unlikely(builder, builder.icmp_signed('<=', n, zero)):
# n <= 0
msg = "empty range for randrange()"
context.call_conv.return_user_exc(builder, ValueError, (msg,))
fnty = ir.FunctionType(ty, [ty, cgutils.true_bit.type])
fn = cgutils.get_or_insert_function(builder.function.module, fnty,
"llvm.ctlz.%s" % ty)
# Since the upper bound is exclusive, we need to subtract one before
# calculating the number of bits. This leads to a special case when
# n == 1; there's only one possible result, so we don't need bits from
# the PRNG. This case is handled separately towards the end of this
# function. CPython's implementation is simpler and just runs another
# iteration of the while loop when the resulting number is too large
# instead of subtracting one, to avoid needing to handle a special
# case. Thus, we only perform this subtraction for the NumPy case.
nm1 = builder.sub(n, one) if state == "np" else n
nbits = builder.trunc(builder.call(fn, [nm1, cgutils.true_bit]), int32_t)
nbits = builder.sub(ir.Constant(int32_t, ty.width), nbits)
rptr = cgutils.alloca_once(builder, ty, name="r")
def get_num():
bbwhile = builder.append_basic_block("while")
bbend = builder.append_basic_block("while.end")
builder.branch(bbwhile)
builder.position_at_end(bbwhile)
r = get_next_int(context, builder, state_ptr, nbits, state == "np")
r = builder.trunc(r, ty)
too_large = builder.icmp_signed('>=', r, n)
builder.cbranch(too_large, bbwhile, bbend)
builder.position_at_end(bbend)
builder.store(r, rptr)
if state == "np":
# Handle n == 1 case, per previous comment.
with builder.if_else(builder.icmp_signed('==', n, one)) as (is_one, is_not_one):
with is_one:
builder.store(zero, rptr)
with is_not_one:
get_num()
else:
get_num()
return builder.add(start, builder.mul(builder.load(rptr), step))
@overload(random.randrange)
def randrange_impl_1(start):
if isinstance(start, types.Integer):
return lambda start: random.randrange(0, start, 1)
@overload(random.randrange)
def randrange_impl_2(start, stop):
if isinstance(start, types.Integer) and isinstance(stop, types.Integer):
return lambda start, stop: random.randrange(start, stop, 1)
def _randrange_preprocessor(bitwidth, ty):
if ty.bitwidth != bitwidth:
return (ir.IRBuilder.sext if ty.signed
else ir.IRBuilder.zext)
else:
return lambda _builder, v, _ty: v
@overload(random.randrange)
def randrange_impl_3(start, stop, step):
if (isinstance(start, types.Integer) and isinstance(stop, types.Integer) and
isinstance(step, types.Integer)):
signed = max(start.signed, stop.signed, step.signed)
bitwidth = max(start.bitwidth, stop.bitwidth, step.bitwidth)
int_ty = types.Integer.from_bitwidth(bitwidth, signed)
llvm_type = ir.IntType(bitwidth)
start_preprocessor = _randrange_preprocessor(bitwidth, start)
stop_preprocessor = _randrange_preprocessor(bitwidth, stop)
step_preprocessor = _randrange_preprocessor(bitwidth, step)
@intrinsic
def _impl(typingcontext, start, stop, step):
def codegen(context, builder, sig, args):
start, stop, step = args
start = start_preprocessor(builder, start, llvm_type)
stop = stop_preprocessor(builder, stop, llvm_type)
step = step_preprocessor(builder, step, llvm_type)
return _randrange_impl(context, builder, start, stop, step,
llvm_type, signed, 'py')
return signature(int_ty, start, stop, step), codegen
return lambda start, stop, step: _impl(start, stop, step)
@overload(random.randint)
def randint_impl_1(a, b):
if isinstance(a, types.Integer) and isinstance(b, types.Integer):
return lambda a, b: random.randrange(a, b + 1, 1)
@overload(np.random.randint)
def np_randint_impl_1(low):
if isinstance(low, types.Integer):
return lambda low: np.random.randint(0, low)
@overload(np.random.randint)
def np_randint_impl_2(low, high):
if isinstance(low, types.Integer) and isinstance(high, types.Integer):
signed = max(low.signed, high.signed)
bitwidth = max(low.bitwidth, high.bitwidth)
int_ty = types.Integer.from_bitwidth(bitwidth, signed)
llvm_type = ir.IntType(bitwidth)
start_preprocessor = _randrange_preprocessor(bitwidth, low)
stop_preprocessor = _randrange_preprocessor(bitwidth, high)
@intrinsic
def _impl(typingcontext, low, high):
def codegen(context, builder, sig, args):
start, stop = args
start = start_preprocessor(builder, start, llvm_type)
stop = stop_preprocessor(builder, stop, llvm_type)
step = ir.Constant(llvm_type, 1)
return _randrange_impl(context, builder, start, stop, step,
llvm_type, signed, 'np')
return signature(int_ty, low, high), codegen
return lambda low, high: _impl(low, high)
@overload(np.random.randint)
def np_randint_impl_3(low, high, size):
if (isinstance(low, types.Integer) and isinstance(high, types.Integer) and
is_nonelike(size)):
return lambda low, high, size: np.random.randint(low, high)
if (isinstance(low, types.Integer) and isinstance(high, types.Integer) and
is_empty_tuple(size)):
# Handle size = ()
return lambda low, high, size: np.array(np.random.randint(low, high))
if (isinstance(low, types.Integer) and isinstance(high, types.Integer) and
(isinstance(size, types.Integer) or (isinstance(size, types.UniTuple)
and isinstance(size.dtype,
types.Integer)))):
bitwidth = max(low.bitwidth, high.bitwidth)
result_type = getattr(np, f'int{bitwidth}')
def _impl(low, high, size):
out = np.empty(size, dtype=result_type)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.randint(low, high)
return out
return _impl
@overload(np.random.uniform)
def np_uniform_impl0():
return lambda: np.random.uniform(0.0, 1.0)
@overload(random.uniform)
def uniform_impl2(a, b):
if isinstance(a, (types.Float, types.Integer)) and isinstance(
b, (types.Float, types.Integer)):
@intrinsic
def _impl(typingcontext, a, b):
low_preprocessor = _double_preprocessor(a)
high_preprocessor = _double_preprocessor(b)
return signature(types.float64, a, b), uniform_impl(
'py', low_preprocessor, high_preprocessor)
return lambda a, b: _impl(a, b)
@overload(np.random.uniform)
def np_uniform_impl2(low, high):
if isinstance(low, (types.Float, types.Integer)) and isinstance(
high, (types.Float, types.Integer)):
@intrinsic
def _impl(typingcontext, low, high):
low_preprocessor = _double_preprocessor(low)
high_preprocessor = _double_preprocessor(high)
return signature(types.float64, low, high), uniform_impl(
'np', low_preprocessor, high_preprocessor)
return lambda low, high: _impl(low, high)
def uniform_impl(state, a_preprocessor, b_preprocessor):
def impl(context, builder, sig, args):
state_ptr = get_state_ptr(context, builder, state)
a, b = args
a = a_preprocessor(builder, a)
b = b_preprocessor(builder, b)
width = builder.fsub(b, a)
r = get_next_double(context, builder, state_ptr)
return builder.fadd(a, builder.fmul(width, r))
return impl
@overload(np.random.uniform)
def np_uniform_impl3(low, high, size):
if (isinstance(low, (types.Float, types.Integer)) and isinstance(
high, (types.Float, types.Integer)) and
is_nonelike(size)):
return lambda low, high, size: np.random.uniform(low, high)
if (isinstance(low, (types.Float, types.Integer)) and isinstance(
high, (types.Float, types.Integer)) and
is_empty_tuple(size)):
# When calling np.random.uniform with size = (), the returned value isn't a
# float like when size = None. Instead, it's an array of shape ()
return lambda low, high, size: np.array(np.random.uniform(low, high))
if (isinstance(low, (types.Float, types.Integer)) and isinstance(
high, (types.Float, types.Integer)) and
(isinstance(size, types.Integer) or (isinstance(size, types.UniTuple)
and isinstance(size.dtype,
types.Integer)))):
def _impl(low, high, size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.uniform(low, high)
return out
return _impl
@overload(random.triangular)
def triangular_impl_2(low, high):
def _impl(low, high):
u = random.random()
c = 0.5
if u > c:
u = 1.0 - u
low, high = high, low
return low + (high - low) * math.sqrt(u * c)
if isinstance(low, (types.Float, types.Integer)) and isinstance(
high, (types.Float, types.Integer)):
return _impl
@overload(random.triangular)
def triangular_impl_3(low, high, mode):
if (isinstance(low, (types.Float, types.Integer)) and isinstance(
high, (types.Float, types.Integer)) and
isinstance(mode, (types.Float, types.Integer))):
def _impl(low, high, mode):
if high == low:
return low
u = random.random()
c = (mode - low) / (high - low)
if u > c:
u = 1.0 - u
c = 1.0 - c
low, high = high, low
return low + (high - low) * math.sqrt(u * c)
return _impl
@overload(np.random.triangular)
def triangular_impl_3(left, mode, right):
if (isinstance(left, (types.Float, types.Integer)) and isinstance(
mode, (types.Float, types.Integer)) and
isinstance(right, (types.Float, types.Integer))):
def _impl(left, mode, right):
if right == left:
return left
u = np.random.random()
c = (mode - left) / (right - left)
if u > c:
u = 1.0 - u
c = 1.0 - c
left, right = right, left
return left + (right - left) * math.sqrt(u * c)
return _impl
@overload(np.random.triangular)
def triangular_impl(left, mode, right, size=None):
if is_nonelike(size):
return lambda left, mode, right, size=None: np.random.triangular(left,
mode,
right)
if is_empty_tuple(size):
# Handle size = ()
return lambda left, mode, right, size=None: np.array(
np.random.triangular(left, mode, right)
)
if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and
isinstance(size.dtype,
types.Integer))):
def _impl(left, mode, right, size=None):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.triangular(left, mode, right)
return out
return _impl
@overload(random.gammavariate)
def gammavariate_impl(alpha, beta):
if isinstance(alpha, (types.Float, types.Integer)) and isinstance(
beta, (types.Float, types.Integer)):
return _gammavariate_impl(random.random)
@overload(np.random.standard_gamma)
@overload(np.random.gamma)
def ol_np_random_gamma1(shape):
if isinstance(shape, (types.Float, types.Integer)):
return lambda shape: np.random.gamma(shape, 1.0)
@overload(np.random.gamma)
def ol_np_random_gamma2(shape, scale):
if isinstance(shape, (types.Float, types.Integer)) and isinstance(
scale, (types.Float, types.Integer)):
fn = register_jitable(_gammavariate_impl(np.random.random))
def impl(shape, scale):
return fn(shape, scale)
return impl
def _gammavariate_impl(_random):
def _impl(alpha, beta):
"""Gamma distribution. Taken from CPython.
"""
SG_MAGICCONST = 1.0 + math.log(4.5)
# alpha > 0, beta > 0, mean is alpha*beta, variance is alpha*beta**2
# Warning: a few older sources define the gamma distribution in terms
# of alpha > -1.0
if alpha <= 0.0 or beta <= 0.0:
raise ValueError('gammavariate: alpha and beta must be > 0.0')
if alpha > 1.0:
# Uses R.C.H. Cheng, "The generation of Gamma
# variables with non-integral shape parameters",
# Applied Statistics, (1977), 26, No. 1, p71-74
ainv = math.sqrt(2.0 * alpha - 1.0)
bbb = alpha - math.log(4.0)
ccc = alpha + ainv
while 1:
u1 = _random()
if not 1e-7 < u1 < .9999999:
continue
u2 = 1.0 - _random()
v = math.log(u1/(1.0-u1))/ainv
x = alpha*math.exp(v)
z = u1*u1*u2
r = bbb+ccc*v-x
if r + SG_MAGICCONST - 4.5*z >= 0.0 or r >= math.log(z):
return x * beta
elif alpha == 1.0:
# expovariate(1)
# Adjust due to cpython
# commit 63d152232e1742660f481c04a811f824b91f6790
return -math.log(1.0 - _random()) * beta
else: # alpha is between 0 and 1 (exclusive)
# Uses ALGORITHM GS of Statistical Computing - Kennedy & Gentle
while 1:
u = _random()
b = (math.e + alpha)/math.e
p = b*u
if p <= 1.0:
x = p ** (1.0/alpha)
else:
x = -math.log((b-p)/alpha)
u1 = _random()
if p > 1.0:
if u1 <= x ** (alpha - 1.0):
break
elif u1 <= math.exp(-x):
break
return x * beta
return _impl
@overload(np.random.gamma)
def gamma_impl(shape, scale, size):
if is_nonelike(size):
return lambda shape, scale, size: np.random.gamma(shape, scale)
if is_empty_tuple(size):
# Handle size = ()
return lambda shape, scale, size: np.array(np.random.gamma(shape, scale))
if isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and
isinstance(size.dtype,
types.Integer)):
def _impl(shape, scale, size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.gamma(shape, scale)
return out
return _impl
@overload(np.random.standard_gamma)
def standard_gamma_impl(shape, size):
if is_nonelike(size):
return lambda shape, size: np.random.standard_gamma(shape)
if is_empty_tuple(size):
# Handle size = ()
return lambda shape, size: np.array(np.random.standard_gamma(shape))
if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple)
and isinstance(size.dtype,
types.Integer))):
def _impl(shape, size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.standard_gamma(shape)
return out
return _impl
@overload(random.betavariate)
def betavariate_impl(alpha, beta):
if isinstance(alpha, (types.Float, types.Integer)) and isinstance(
beta, (types.Float, types.Integer)):
return _betavariate_impl(random.gammavariate)
@overload(np.random.beta)
def ol_np_random_beta(a, b):
if isinstance(a, (types.Float, types.Integer)) and isinstance(
b, (types.Float, types.Integer)):
fn = register_jitable(_betavariate_impl(np.random.gamma))
def impl(a, b):
return fn(a, b)
return impl
def _betavariate_impl(gamma):
def _impl(alpha, beta):
"""Beta distribution. Taken from CPython.
"""
# This version due to Janne Sinkkonen, and matches all the std
# texts (e.g., Knuth Vol 2 Ed 3 pg 134 "the beta distribution").
y = gamma(alpha, 1.)
if y == 0.0:
return 0.0
else:
return y / (y + gamma(beta, 1.))
return _impl
@overload(np.random.beta)
def beta_impl(a, b, size):
if is_nonelike(size):
return lambda a, b, size: np.random.beta(a, b)
if is_empty_tuple(size):
# When calling np.random.beta with size = (), the returned value isn't a
# float like when size = None. Instead, it's an array of shape ()
return lambda a, b, size: np.array(np.random.beta(a, b))
if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple)
and isinstance(size.dtype,
types.Integer))):
def _impl(a, b, size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.beta(a, b)
return out
return _impl
@overload(random.expovariate)
def expovariate_impl(lambd):
if isinstance(lambd, types.Float):
def _impl(lambd):
"""Exponential distribution. Taken from CPython.
"""
# lambd: rate lambd = 1/mean
# ('lambda' is a Python reserved word)
# we use 1-random() instead of random() to preclude the
# possibility of taking the log of zero.
return -math.log(1.0 - random.random()) / lambd
return _impl
@overload(np.random.exponential)
def exponential_impl(scale):
if isinstance(scale, (types.Float, types.Integer)):
def _impl(scale):
return -math.log(1.0 - np.random.random()) * scale
return _impl
@overload(np.random.exponential)
def exponential_impl(scale, size):
if is_nonelike(size):
return lambda scale, size: np.random.exponential(scale)
if is_empty_tuple(size):
# Handle size = ()
return lambda scale, size: np.array(np.random.exponential(scale))
if (isinstance(size, types.Integer) or (isinstance(size, types.UniTuple) and
isinstance(size.dtype,
types.Integer))):
def _impl(scale, size):
out = np.empty(size)
out_flat = out.flat
for idx in range(out.size):
out_flat[idx] = np.random.exponential(scale)
return out
return _impl
@overload(np.random.standard_exponential)
@overload(np.random.exponential)
def exponential_impl():
def _impl():
return -math.log(1.0 - np.random.random())
return _impl