How to use randomgen - 10 common examples

To help you get started, we’ve selected a few randomgen examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bashtage / randomgen / tools / practrand-driver.py View on Github external
def jumped_state(bit_generator, n_streams=2, entropy=None):
    bitgen = getattr(rg, bit_generator)
    config = CONFIG[bitgen]
    seed = config["seed"]
    if entropy is None:
        entropy = rg.random_entropy(seed // 32)
        if config["seed_size"] == 64:
            entropy = entropy.view(np.uint64)
            if config["seed"] == 64:
                entropy = entropy[0]
        elif config["seed_size"] == 128:
            entropy = int(entropy[0]) + int(entropy[1]) * 2 ** 64
        elif config["seed_size"] == 256:
            base = int(0)
            for i in range(4):
                base += int(entropy[i]) * (2 ** (64 * i))
            entropy = base
        elif config["seed_size"] != 32:
            raise NotImplementedError
    else:
        seed_size = config["seed_size"]
        if seed_size in (32, 64):
github bashtage / randomgen / tools / practrand-driver.py View on Github external
BUFFER_SIZE = 256 * 2 ** 20

DESCRIPTION = """
A driver that simplifies testing bit generators using PractRand.
"""

CONFIG = {
    rg.PCG32: {"output": 32, "seed": 64, "seed_size": 64},
    rg.PCG64: {"output": 64, "seed": 128, "seed_size": 128},
    rg.ThreeFry: {"output": 64, "seed": 256, "seed_size": 64},
    rg.Xoshiro256: {"output": 64, "seed": 256, "seed_size": 64},
    rg.Philox: {"output": 64, "seed": 256, "seed_size": 64},
    rg.SFMT: {"output": 64, "seed": 128, "seed_size": 32},
    rg.LXM: {"output": 64, "seed": 128, "seed_size": 32},
    rg.SFC64: {"output": 64, "seed": 128, "seed_size": 32},
    rg.AESCounter: {"output": 64, "seed": 128, "seed_size": 32},
}


def reorder_bytes(a):
    dtype = a.dtype
    assert dtype in (np.uint32, np.uint64)
    cols = 8 if dtype == np.uint64 else 4
    a = a.view(np.uint8).reshape((-1, cols))
    return a.ravel("F").view(dtype)


def pack_bits(a, bits):
    print("Packing bits")
    assert bits > 32
    nitems = a.shape[0]
    block_rows = nitems // 64
github firedrakeproject / firedrake / tests / randomfunctiongen / test_randomfunction.py View on Github external
def test_randomfunc_parallel_pcg64():

    mesh = UnitSquareMesh(10, 10)
    V0 = VectorFunctionSpace(mesh, "CG", 1)
    V1 = FunctionSpace(mesh, "CG", 1)
    V = V0 * V1

    seed = 123456789

    # original
    from mpi4py import MPI
    rg_base = randomgen.PCG64(seed=seed, inc=MPI.COMM_WORLD.rank).generator

    # Firedrake wrapper
    rg_wrap = PCG64(seed=seed).generator

    for i in range(1, 10):
        f = rg_wrap.beta(V, 0.3, 0.5)
        with f.dat.vec_ro as v:
            assert np.allclose(rg_base.beta(0.3, 0.5, size=(v.local_size,)), v.array[:])

    rg_base.seed(seed=12345678910, inc=MPI.COMM_WORLD.rank)
    rg_wrap.seed(seed=12345678910)
    for i in range(1, 10):
        f = rg_wrap.beta(V, 0.3, 0.5)
        with f.dat.vec_ro as v:
            assert np.allclose(rg_base.beta(0.3, 0.5, size=(v.local_size,)), v.array[:])
github bashtage / randomgen / tools / prng-tester.py View on Github external
def configure_stream(
    bit_gen, kwargs=None, jumped=False, streams=8196, entropy=DEFAULT_ENTOPY
):
    bit_generator = bit_gen.__name__
    extra_code = extra_initialization = ""
    if bit_gen == SFC64 and kwargs["k"] == "weyl":
        extra_code = f"""\
base = rg.SFC64(seed_seq)
weyl = base.weyl_increments({streams})
bitgens = [rg.SFC64(seed_seq, k=k) for k in retain]
        """
    elif bit_gen == DSFMT:
        bit_generator = "Wrapper32"
        extra_initialization = DSFMT_WRAPPER
        # return configure_dsfmt(streams, entropy=entropy)
    kwargs = {} if kwargs is None else kwargs
    kwargs_repr = str(kwargs)
    return TEMPLATE.render(
        bit_generator=bit_generator,
        entropy=entropy,
        jumped=jumped,
        streams=streams,
        kwargs=kwargs_repr,
        output=OUTPUT[bit_gen],
        extra_initialization=extra_initialization,
        extra_code=extra_code,
    )
github bashtage / randomgen / tools / test-seed-correlation.py View on Github external
args = [value for value in config.values()]
            for arg_set in itertools.product(*args):
                kwargs = {key: arg for key, arg in zip(config.keys(), arg_set)}
                key = "-".join(
                    [bit_generator]
                    + [f"{key}-{value}" for key, value in kwargs.items()]
                )
                parameters[key] = (bitgen, kwargs)
        else:
            parameters[key] = (bitgen, {})
    for key in parameters:
        extra_initialization = ""
        bitgen, kwargs = parameters[key]
        bit_generator = bitgen.__name__
        kwargs_repr = repr(kwargs)
        if bitgen == DSFMT:
            extra_initialization = DSFMT_WRAPPER
            bit_generator = "Wrapper32"
        streams[key] = TEMPLATE.render(
            streams=num_streams,
            kwargs=kwargs_repr,
            bit_generator=bit_generator,
            output=OUTPUT[bitgen],
            extra_initialization=extra_initialization,
            sequential=sequential,
        )
    return streams
github bashtage / randomgen / tools / prng-tester.py View on Github external
def configure_stream(
    bit_gen, kwargs=None, jumped=False, streams=8196, entropy=DEFAULT_ENTOPY
):
    bit_generator = bit_gen.__name__
    extra_code = extra_initialization = ""
    if bit_gen == SFC64 and kwargs["k"] == "weyl":
        extra_code = f"""\
base = rg.SFC64(seed_seq)
weyl = base.weyl_increments({streams})
bitgens = [rg.SFC64(seed_seq, k=k) for k in retain]
        """
    elif bit_gen == DSFMT:
        bit_generator = "Wrapper32"
        extra_initialization = DSFMT_WRAPPER
        # return configure_dsfmt(streams, entropy=entropy)
    kwargs = {} if kwargs is None else kwargs
    kwargs_repr = str(kwargs)
    return TEMPLATE.render(
        bit_generator=bit_generator,
        entropy=entropy,
        jumped=jumped,
        streams=streams,
github bashtage / randomgen / randomgen / examples / numba / extending.py View on Github external
import datetime as dt

import numba as nb
import numpy as np

from randomgen import Xoroshiro128

x = Xoroshiro128()
f = x.ctypes.next_uint32
s = x.ctypes.state


@nb.jit(nopython=True)
def bounded_uint(lb, ub, state):
    mask = delta = ub - lb
    mask |= mask >> 1
    mask |= mask >> 2
    mask |= mask >> 4
    mask |= mask >> 8
    mask |= mask >> 16

    val = f(state) & mask
    while val > delta:
        val = f(state) & mask
github bashtage / randomgen / randomgen / examples / numba / extending.py View on Github external
import datetime as dt

import numba as nb
import numpy as np

from randomgen import Xoroshiro128

x = Xoroshiro128()
f = x.ctypes.next_uint32
s = x.ctypes.state


@nb.jit(nopython=True)
def bounded_uint(lb, ub, state):
    mask = delta = ub - lb
    mask |= mask >> 1
    mask |= mask >> 2
    mask |= mask >> 4
    mask |= mask >> 8
    mask |= mask >> 16

    val = f(state) & mask
    while val > delta:
        val = f(state) & mask
github bashtage / randomgen / randomgen / examples / numba / extending_distributions.py View on Github external
from randomgen import Xoroshiro128

ffi = FFI()
if os.path.exists("./distributions.dll"):
    lib = ffi.dlopen("./distributions.dll")
elif os.path.exists("./libdistributions.so"):
    lib = ffi.dlopen("./libdistributions.so")
else:
    raise RuntimeError("Required DLL/so file was not found.")

ffi.cdef(
    """
double random_gauss_zig(void *bitgen_state);
"""
)
x = Xoroshiro128()
xffi = x.cffi
bit_generator = xffi.bit_generator

random_gauss_zig = lib.random_gauss_zig


def normals(n, bit_generator):
    out = np.empty(n)
    for i in range(n):
        out[i] = random_gauss_zig(bit_generator)
    return out


normalsj = nb.jit(normals, nopython=True)

# Numba requires a memory address for void *
github numpy / numpy / _randomgen / doc / source / conf.py View on Github external
import randomgen

# -- Project information -----------------------------------------------------

project = 'RandomGen'
copyright = '2018, Kevin Sheppard'
author = 'Kevin Sheppard'

# The short X.Y version.

version = randomgen.__version__
if '+' in version:
    version = version.split('+')
    version = ''.join((version[0], ' (+', version[1].split('.')[0], ')'))
# The full version, including alpha/beta/rc tags.
release = randomgen.__version__

# -- General configuration ---------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.napoleon',
    'sphinx.ext.autodoc',
    'sphinx.ext.extlinks',
    'sphinx.ext.todo',
    'sphinx.ext.doctest',