コード例 #1
0
    def test_array(self):
        s = RandomGenerator(MT19937(range(10)))
        assert_equal(s.randint(1000), 468)
        s = np.random.RandomState(range(10))
        assert_equal(s.randint(1000), 468)

        s = RandomGenerator(MT19937(np.arange(10)))
        assert_equal(s.randint(1000), 468)
        s = RandomGenerator(MT19937([0]))
        assert_equal(s.randint(1000), 973)
        s = RandomGenerator(MT19937([4294967295]))
        assert_equal(s.randint(1000), 265)
コード例 #2
0
    def test_array(self):
        s = Generator(MT19937(range(10), mode="legacy"))
        assert_equal(s.integers(1000), 468)
        s = np.random.RandomState(range(10))
        assert_equal(s.randint(1000), 468)

        s = Generator(MT19937(np.arange(10), mode="legacy"))
        assert_equal(s.integers(1000), 468)
        s = Generator(MT19937([0], mode="legacy"))
        assert_equal(s.integers(1000), 973)
        s = Generator(MT19937([4294967295], mode="legacy"))
        assert_equal(s.integers(1000), 265)
コード例 #3
0
    def test_scalar(self):
        s = RandomGenerator(MT19937(0))
        assert_equal(s.randint(1000), 684)
        s1 = np.random.RandomState(0)
        assert_equal(s1.randint(1000), 684)
        assert_equal(s1.randint(1000), s.randint(1000))

        s = RandomGenerator(MT19937(4294967295))
        assert_equal(s.randint(1000), 419)
        s1 = np.random.RandomState(4294967295)
        assert_equal(s1.randint(1000), 419)
        assert_equal(s1.randint(1000), s.randint(1000))

        self.rg.seed(4294967295)
        self.nprs.seed(4294967295)
        self._is_state_common()
コード例 #4
0
def test_complex_normal_size(mv_seed):
    random = ExtendedGenerator(MT19937(mv_seed, mode="legacy"))
    state = random.state
    loc = np.ones((1, 2))
    gamma = np.ones((3, 1))
    relation = 0.5 * np.ones((3, 2))
    actual = random.complex_normal(loc=loc, gamma=gamma, relation=relation)
    desired = np.array([
        [
            1.393937478212015 - 0.31374589731830593j,
            0.9474905694736895 - 0.16424530802218726j,
        ],
        [
            1.119247463119766 + 0.023956373851168843j,
            0.8776366291514774 + 0.2865220655803411j,
        ],
        [
            0.5515508326417458 - 0.15986016780453596j,
            -0.6803993941303332 + 1.1782711493556892j,
        ],
    ])
    assert_array_almost_equal(actual, desired, decimal=15)

    random.state = state
    actual = random.complex_normal(loc=loc,
                                   gamma=1.0,
                                   relation=0.5,
                                   size=(3, 2))
    assert_array_almost_equal(actual, desired, decimal=15)
コード例 #5
0
    def test_scalar(self):
        s = Generator(MT19937(0, mode="legacy"))
        assert_equal(s.integers(1000), 684)
        s1 = np.random.RandomState(0)
        assert_equal(s1.randint(1000), 684)
        assert_equal(s1.randint(1000), s.integers(1000))

        s = Generator(MT19937(4294967295, mode="legacy"))
        assert_equal(s.integers(1000), 419)
        s1 = np.random.RandomState(4294967295)
        assert_equal(s1.randint(1000), 419)
        assert_equal(s1.randint(1000), s.integers(1000))

        self.rg.bit_generator.seed(4294967295)
        self.nprs.seed(4294967295)
        self._is_state_common()
コード例 #6
0
 def test_call_within_randomstate(self):
     # Check that custom RandomState does not call into global state
     m = RandomGenerator(MT19937())  # mt19937.RandomState()
     res = np.array([0, 8, 7, 2, 1, 9, 4, 7, 0, 3])
     for i in range(3):
         mt19937.seed(i)
         m.seed(4321)
         # If m.state is not honored, the result will change
         assert_array_equal(m.choice(10, size=10, p=np.ones(10)/10.), res)
コード例 #7
0
def test_pickle_and_copy(seed):
    gen = ExtendedGenerator(MT19937(seed, mode="legacy"))
    reloaded = pickle.loads(pickle.dumps(gen))
    assert isinstance(reloaded, ExtendedGenerator)
    copied = copy.deepcopy(gen)
    gen_rv = gen.uintegers(10, bits=64)
    reloaded_rv = reloaded.uintegers(10, bits=64)
    copied_rv = copied.uintegers(10, bits=64)
    assert_equal(gen_rv, reloaded_rv)
    assert_equal(gen_rv, copied_rv)
コード例 #8
0
def test_multivariate_normal_basic_stats(seed, method):
    random = ExtendedGenerator(MT19937(seed, mode="sequence"))
    n_s = 1000
    mean = np.array([1, 2])
    cov = np.array([[2, 1], [1, 2]])
    s = random.multivariate_normal(mean, cov, size=(n_s, ), method=method)
    s_center = s - mean
    cov_emp = (s_center.T @ s_center) / (n_s - 1)
    # these are pretty loose and are only designed to detect major errors
    assert np.all(np.abs(s_center.mean(-2)) < 0.1)
    assert np.all(np.abs(cov_emp - cov) < 0.2)
コード例 #9
0
        self._bins = 10 * (5**(level_obj))

    def solve(self, sample):
        solution = np.histogram(sample, self._bins, (0, 1000))
        ans = sum(i > 0 for i in solution[0])
        return ans


def lvl_maker(level_f, level_c, comm=MPI.COMM_WORLD):
    if level_c < 0:
        return level_f, None
    else:
        return level_f, level_c


rg = RandomGenerator(MT19937(12345))


def samp(level, level2):
    ans = [rg.random_sample() * 1000 for i in range(10)]
    if level2 == None:
        return ans, None
    return ans, ans


def general_test():
    # Levels and repetitions
    levels = 4
    repetitions = [1000, 500, 1000, 1000]
    MLMCprob = MLMC_Problem(binProblem, samp, lvl_maker)
    MLMCsolv = MLMC_Solver(MLMCprob, levels, repetitions)
コード例 #10
0
from __future__ import division, absolute_import, print_function

import sys
from numpy.testing import (assert_, assert_array_equal)
from numpy.compat import long
import numpy as np
import pytest
from randomgen import RandomGenerator, MT19937

mt19937 = RandomGenerator(MT19937())


class TestRegression(object):

    def test_VonMises_range(self):
        # Make sure generated random variables are in [-pi, pi].
        # Regression test for ticket #986.
        for mu in np.linspace(-7., 7., 5):
            r = mt19937.vonmises(mu, 1, 50)
            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))

    def test_hypergeometric_range(self):
        # Test for ticket #921
        assert_(np.all(mt19937.hypergeometric(3, 18, 11, size=10) < 4))
        assert_(np.all(mt19937.hypergeometric(18, 3, 11, size=10) > 0))

        # Test for ticket #5623
        args = [
            (2**20 - 2, 2**20 - 2, 2**20 - 2),  # Check for 32-bit systems
        ]
        is_64bits = sys.maxsize > 2**32
コード例 #11
0
# Code to estimate mixture entropy using Monte Carlo sampling

import numpy as np
import scipy
from entropy import pairwise_distance2_np

from randomgen import RandomGenerator, MT19937
rnd = RandomGenerator(MT19937())


def get_mc_entropy(mx, var):
    n, d = mx.shape
    mx2 = mx + rnd.standard_normal(mx.shape, dtype=np.float32) * np.sqrt(var)

    dist_norm = pairwise_distance2_np(mx, mx2) / (-2.0 * var)

    const = -0.5 * d * np.log(2.0 * np.pi * var) - np.log(n)
    logprobs = const + scipy.special.logsumexp(dist_norm, axis=0)

    return -np.mean(logprobs)
コード例 #12
0
import numpy as np
from numpy.compat import long
from numpy.testing import assert_, assert_array_equal
import pytest

from randomgen import MT19937, Generator

mt19937 = Generator(MT19937(mode="legacy"))


class TestRegression(object):
    def test_VonMises_range(self):
        # Make sure generated random variables are in [-pi, pi].
        # Regression test for ticket #986.
        for mu in np.linspace(-7.0, 7.0, 5):
            r = mt19937.vonmises(mu, 1, 50)
            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))

    def test_hypergeometric_range(self):
        # Test for ticket #921
        assert_(np.all(mt19937.hypergeometric(3, 18, 11, size=10) < 4))
        assert_(np.all(mt19937.hypergeometric(18, 3, 11, size=10) > 0))

        # Test for ticket #5623
        args = (2**20 - 2, 2**20 - 2, 2**20 - 2)  # Check for 32-bit systems
        assert_(mt19937.hypergeometric(*args) > 0)

    def test_logseries_convergence(self):
        # Test for ticket #923
        N = 1000
        mt19937.bit_generator.seed(0)
コード例 #13
0
import sys

import numpy as np
from numpy.compat import long
from numpy.testing import assert_, assert_array_equal
import pytest

from randomgen import MT19937, Generator

mt19937 = Generator(MT19937())


class TestRegression(object):
    def test_VonMises_range(self):
        # Make sure generated random variables are in [-pi, pi].
        # Regression test for ticket #986.
        for mu in np.linspace(-7., 7., 5):
            r = mt19937.vonmises(mu, 1, 50)
            assert_(np.all(r > -np.pi) and np.all(r <= np.pi))

    def test_hypergeometric_range(self):
        # Test for ticket #921
        assert_(np.all(mt19937.hypergeometric(3, 18, 11, size=10) < 4))
        assert_(np.all(mt19937.hypergeometric(18, 3, 11, size=10) > 0))

        # Test for ticket #5623
        args = [
            (2**20 - 2, 2**20 - 2, 2**20 - 2),  # Check for 32-bit systems
        ]
        is_64bits = sys.maxsize > 2**32
        if is_64bits and sys.platform != 'win32':
コード例 #14
0
            state["key"] = np.asarray(state["key"], dtype="uint32")
            state = {"key": [], "pos": -1}
            states.append(state)
    return states[:-1], pf


values: Dict[Tuple[str, Tuple[int, ...], int], Dict] = {}
for poly in ("poly-128", "clist_mt19937"):
    shutil.copy(f"{poly}.txt", "jump-poly.txt")
    fn = "_jump_tester" if poly == "clist_mt19937" else "jumped"
    for seed, step in zip(SEEDS, STEPS):
        seed_tpl = (seed,) if isinstance(seed, int) else tuple(seed)
        key = (fn, seed_tpl, step)
        values[key] = {}
        np_mt19937 = np.random.MT19937(seed)
        mt19937 = MT19937(mode="sequence")
        mt19937.state = np_mt19937.state
        mt19937.random_raw(step)
        file_name = f"state-{seed}-{step}.csv"
        save_state(mt19937, file_name=file_name)
        hash = hashlib.md5(mt19937.state["state"]["key"])
        values[key]["initial"] = {
            "key_md5": hash.hexdigest(),
            "pos": mt19937.state["state"]["pos"],
        }
        if os.path.exists("state.txt"):
            os.unlink("state.txt")
        shutil.copy(file_name, "state.txt")
        out = subprocess.run(EXECUTABLE, stdout=subprocess.PIPE)
        parsed, pf = parse_output(out.stdout.decode("utf8"))
        hash = hashlib.md5(parsed[-1]["key"])
コード例 #15
0
def test_set_get_state(seed):
    state = _mt19937.state
    gen = ExtendedGenerator(MT19937(seed, mode="legacy"))
    gen.state = state
    assert_equal(gen.state["state"]["key"], state["state"]["key"])
    assert_equal(gen.state["state"]["pos"], state["state"]["pos"])
コード例 #16
0
SEED = 1234567890
MV_SEED = 123456789


@pytest.fixture(scope="module")
def seed():
    return SEED


@pytest.fixture(scope="module")
def mv_seed():
    return MV_SEED


_mt19937 = MT19937(SEED, mode="legacy")
random = ExtendedGenerator(_mt19937)

NP_LT_118 = LooseVersion(np.__version__) < LooseVersion("1.18.0")


@pytest.mark.skipif(NP_LT_118, reason="Can only test with NumPy >= 1.18")
@pytest.mark.parametrize("method", ["svd", "eigh", "cholesky"])
def test_multivariate_normal_method(seed, method):
    from numpy.random import MT19937 as NPMT19937

    random = ExtendedGenerator(NPMT19937(seed))
    mean = (0.123456789, 10)
    cov = [[1, 0], [0, 1]]
    size = (3, 2)
    actual = random.multivariate_normal(mean, cov, size, method=method)