LINE Solver
MATLAB API documentation
Loading...
Searching...
No Matches
NumpyRandomState.m
1classdef NumpyRandomState < handle
2 % NumpyRandomState Bit-exact port of the subset of numpy.random.RandomState
3 % consumed by scipy's differential_evolution. Backed by opt.de.MT19937.
4 %
5 % Implements random_sample, uniform, the default-dtype randint (32-bit
6 % masked rejection), and shuffle/permutation (Fisher-Yates driven by
7 % random_interval), each reproducing numpy's exact draw sequence and word
8 % consumption, so the optimizer follows the identical trajectory to the
9 % native-Python line-opt for a given integer seed.
10
11 properties
12 gen % opt.de.MT19937 handle
13 end
14
15 methods
16 function obj = NumpyRandomState(seed)
17 obj.gen = opt.de.MT19937(seed);
18 end
19
20 function d = randomSample(obj)
21 a = double(bitshift(obj.gen.nextUint32(), -5)); % 27 bits
22 b = double(bitshift(obj.gen.nextUint32(), -6)); % 26 bits
23 d = (a * 67108864 + b) / 9007199254740992;
24 end
25
26 function out = randomSampleN(obj, n)
27 out = zeros(1, n);
28 for i = 1:n
29 out(i) = obj.randomSample();
30 end
31 end
32
33 function d = uniformScalar(obj, low, high)
34 d = low + (high - low) * obj.randomSample();
35 end
36
37 function out = uniformN(obj, low, high, n)
38 out = zeros(1, n);
39 for i = 1:n
40 out(i) = low + (high - low) * obj.randomSample();
41 end
42 end
43
44 function m = fillMask(~, v)
45 v = uint64(v);
46 v = bitor(v, bitshift(v, -1));
47 v = bitor(v, bitshift(v, -2));
48 v = bitor(v, bitshift(v, -4));
49 v = bitor(v, bitshift(v, -8));
50 v = bitor(v, bitshift(v, -16));
51 m = v;
52 end
53
54 function v = randint(obj, low, high)
55 rng_ = uint64(high) - uint64(1) - uint64(low);
56 if rng_ == 0
57 v = low;
58 return;
59 end
60 mask = obj.fillMask(rng_);
61 while true
62 w = uint64(obj.gen.nextUint32());
63 val = bitand(w, mask);
64 if val <= rng_
65 v = double(low) + double(val);
66 return;
67 end
68 end
69 end
70
71 function v = randomInterval(obj, maxv)
72 maxv = uint64(maxv);
73 if maxv == 0
74 v = 0;
75 return;
76 end
77 mask = obj.fillMask(maxv);
78 while true
79 w = uint64(obj.gen.nextUint32());
80 val = bitand(w, mask);
81 if val <= maxv
82 v = double(val);
83 return;
84 end
85 end
86 end
87
88 function arr = shuffle(obj, arr)
89 n = numel(arr);
90 for p = n:-1:2
91 jj = obj.randomInterval(uint64(p - 1)); % 0-based j in [0, p-1]
92 tmp = arr(p);
93 arr(p) = arr(jj + 1);
94 arr(jj + 1) = tmp;
95 end
96 end
97
98 function arr = permutation(obj, n)
99 arr = 0:(n - 1);
100 arr = obj.shuffle(arr);
101 end
102 end
103end
Definition Station.m:245