Exemplo n.º 1
0
def test_randomfunc(brng, meth_args):

    meth, args = meth_args

    mesh = UnitSquareMesh(10, 10)
    V0 = VectorFunctionSpace(mesh, "CG", 1)
    V1 = FunctionSpace(mesh, "CG", 1)
    V = V0 * V1
    seed = 123456789
    # Original
    bgen = getattr(randomgen, brng)(seed=seed)
    if brng == 'PCG64':
        state = bgen.state
        state['state'] = {'state': seed, 'inc': V.comm.Get_rank()}
        bgen.state = state
    rg_base = randomgen.Generator(bgen)
    # Firedrake wrapper
    fgen = getattr(randomfunctiongen, brng)(seed=seed)
    if brng == 'PCG64':
        state = fgen.state
        state['state'] = {'state': seed, 'inc': V.comm.Get_rank()}
        fgen.state = state
    rg_wrap = randomfunctiongen.Generator(fgen)
    for i in range(1, 10):
        f = getattr(rg_wrap, meth)(V, *args)
        with f.dat.vec_ro as v:
            if meth in ('rand', 'randn'):
                assert np.allclose(getattr(rg_base, meth)(v.local_size), v.array[:])
            else:
                kwargs = {'size': (v.local_size, )}
                assert np.allclose(getattr(rg_base, meth)(*args, **kwargs), v.array[:])
Exemplo n.º 2
0
 def __init__(self, n, p):
     if n < 2:
         raise Exception('Nodes need to be greater than 2')
         n = 2
     self.nodes_len = n
     self.p = p
     self.nodes = []
     # Unique random generator for the class
     self.rg = rdm.Generator(rdm.SFC64())
     self.G, self.G_deg = self.gen_random_graph(n, p, self.rg)
     self.index = 0
     self.convex = False
     if n == self.BFS(self.G):
         self.convex = True
Exemplo n.º 3
0
def gen_data(seed=97006855):
    n, m, l = 512, 256, 2
    mu = 1e-2
    generator = random.Generator(random.MT19937(seed=seed))
    A = generator.standard_normal(size=(m, n))
    k = round(n * 0.1)
    p = generator.permutation(n)[:k]
    u = np.zeros(shape=(n, l))
    u[p, :] = generator.standard_normal(size=(k, l))  # ground truth
    b = np.matmul(A, u)
    x0 = generator.standard_normal(size=(n, l))
    errfun = lambda x1, x2: norm(x1 - x2, 'fro') / (1 + norm(x1, 'fro'))
    errfun_exact = lambda x: norm(x - u, 'fro') / (1 + norm(x, 'fro'))
    sparsity = lambda x: np.sum(np.abs(x) > 1e-6 * np.max(np.abs(x))) / (n * l)
    return n, m, l, mu, A, b, u, x0, errfun, errfun_exact, sparsity
Exemplo n.º 4
0
def test_randomfunc_parallel_philox():
    mesh = UnitSquareMesh(10, 10)
    V0 = VectorFunctionSpace(mesh, "CG", 1)
    V1 = FunctionSpace(mesh, "CG", 1)
    V = V0 * V1

    key_size = 2
    # Original
    key = np.zeros(key_size, dtype=np.uint64)
    key[0] = V.comm.Get_rank()
    rg_base = randomgen.Generator(randomgen.Philox(counter=12345678910, key=key))
    # Firedrake wrapper
    rg_wrap = randomfunctiongen.Generator(randomfunctiongen.Philox(counter=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[:])
Exemplo n.º 5
0
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
    bgen = randomgen.PCG64(seed=seed)
    state = bgen.state
    state['state'] = {'state': seed, 'inc': V.comm.Get_rank()}
    bgen.state = state
    rg_base = randomgen.Generator(bgen)
    # Firedrake wrapper
    fgen = randomfunctiongen.PCG64(seed=seed)
    state = fgen.state
    state['state'] = {'state': seed, 'inc': V.comm.Get_rank()}
    fgen.state = state
    rg_wrap = randomfunctiongen.Generator(fgen)
    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[:])
Exemplo n.º 6
0
def test_randomgen_brng(brng, meth_args_kwargs):

    meth, args, kwargs = meth_args_kwargs

    seed = 123456789
    # Original
    bgen = getattr(randomgen, brng)(seed=seed)
    if brng == 'PCG64':
        state = bgen.state
        state['state'] = {'state': seed, 'inc': 0}
        bgen.state = state
    rg_base = randomgen.Generator(bgen)
    # Firedrake wrapper
    fgen = getattr(randomfunctiongen, brng)(seed=seed)
    if brng == 'PCG64':
        state = fgen.state
        state['state'] = {'state': seed, 'inc': 0}
        fgen.state = state
    rg_wrap = randomfunctiongen.Generator(fgen)

    if meth == 'bytes':
        a0 = getattr(rg_base, meth)(17)
        a1 = getattr(rg_wrap, meth)(17)
        assert a0 == a1
        return
    elif meth == 'shuffle':
        arr0 = np.arange(17)
        arr1 = np.arange(17)
        getattr(rg_base, meth)(arr0)
        getattr(rg_wrap, meth)(arr1)
        assert np.allclose(arr0, arr1)
        return

    for i in range(1, 10):
        assert np.allclose(
            getattr(rg_base, meth)(*args, **kwargs),
            getattr(rg_wrap, meth)(*args, **kwargs))
Exemplo n.º 7
0
def streamplot(function,
               resolution=None,
               min_length=None,
               max_time=None,
               start_width=0.5,
               end_width=1.5,
               tolerance=3e-3,
               loc_tolerance=1e-10,
               seed=None,
               complex_component="real",
               **kwargs):
    r"""Create a streamline plot of a vector field

    Similar to matplotlib :func:`streamplot <matplotlib.pyplot.streamplot>`

    :arg function: the Firedrake :class:`~.Function` to plot
    :arg resolution: minimum spacing between streamlines (defaults to domain size / 20)
    :arg min_length: minimum length of a streamline (defaults to 4x resolution)
    :arg max_time: maximum time to integrate a streamline
    :arg start_width: line width at beginning of streamline
    :arg end_width: line width at end of streamline, to convey direction
    :arg tolerance: dimensionless tolerance for adaptive ODE integration
    :arg loc_tolerance: point location tolerance for :meth:`~firedrake.functions.Function.at`
    :kwarg complex_component: If plotting complex data, which
        component? (``'real'`` or ``'imag'``). Default is ``'real'``.
    :kwarg kwargs: same as for matplotlib :class:`~matplotlib.collections.LineCollection`
    """
    if function.ufl_shape != (2, ):
        raise ValueError("Streamplot only defined for 2D vector fields!")

    axes = kwargs.pop("axes", None)
    if axes is None:
        figure = plt.figure()
        axes = figure.add_subplot(111)

    mesh = function.ufl_domain()
    if resolution is None:
        coords = toreal(mesh.coordinates.dat.data_ro, "real")
        resolution = (coords.max(axis=0) - coords.min(axis=0)).max() / 20

    if min_length is None:
        min_length = 4 * resolution

    if max_time is None:
        area = assemble(Constant(1) * dx(mesh))
        average_speed = np.sqrt(
            assemble(inner(function, function) * dx) / area)
        max_time = 50 * min_length / average_speed

    streamplotter = Streamplotter(function,
                                  resolution,
                                  min_length,
                                  max_time,
                                  tolerance,
                                  loc_tolerance,
                                  complex_component=complex_component)

    # TODO: better way of seeding start points
    shape = streamplotter._grid.shape
    xmin = streamplotter._grid_point((0, 0))
    xmax = streamplotter._grid_point((shape[0] - 2, shape[1] - 2))
    X, Y = np.meshgrid(np.linspace(xmin[0], xmax[0], shape[0] - 2),
                       np.linspace(xmin[1], xmax[1], shape[1] - 2))
    start_points = np.vstack((X.ravel(), Y.ravel())).T

    # Randomly shuffle the start points
    generator = randomgen.Generator(randomgen.MT19937(seed))
    for x in generator.permutation(np.array(start_points)):
        streamplotter.add_streamline(x)

    # Colors are determined by the speed, thicknesses by arc length
    speeds = []
    widths = []
    for streamline in streamplotter.streamlines:
        velocity = toreal(
            np.array(function.at(streamline, tolerance=loc_tolerance)),
            complex_component)
        speed = np.sqrt(np.sum(velocity**2, axis=1))
        speeds.extend(speed[:-1])

        delta = np.sqrt(np.sum(np.diff(streamline, axis=0)**2, axis=1))
        arc_length = np.cumsum(delta)
        length = arc_length[-1]
        s = arc_length / length
        linewidth = (1 - s) * start_width + s * end_width
        widths.extend(linewidth)

    points = []
    for streamline in streamplotter.streamlines:
        pts = streamline.reshape(-1, 1, 2)
        points.extend(np.hstack((pts[:-1], pts[1:])))

    speeds = np.array(speeds)
    widths = np.array(widths)

    points = np.asarray(points)
    vmin = kwargs.pop("vmin", speeds.min())
    vmax = kwargs.pop("vmax", speeds.max())
    norm = kwargs.pop("norm", matplotlib.colors.Normalize(vmin=vmin,
                                                          vmax=vmax))
    cmap = plt.get_cmap(kwargs.pop("cmap", None))

    collection = LineCollection(points, cmap=cmap, norm=norm, linewidth=widths)
    collection.set_array(speeds)
    axes.add_collection(collection)

    _autoscale_view(axes, function.ufl_domain().coordinates.dat.data_ro)
    return collection
Exemplo n.º 8
0
def test_randomfunc(brng, meth):

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

    seed = 123456789
    # Original
    bgen = getattr(randomgen, brng)(seed=seed)
    if brng == 'PCG64':
        state = bgen.state
        state['state'] = {'state': seed, 'inc': V.comm.Get_rank()}
        bgen.state = state
    rg_base = randomgen.Generator(bgen)
    # Firedrake wrapper
    fgen = getattr(randomfunctiongen, brng)(seed=seed)
    if brng == 'PCG64':
        state = fgen.state
        state['state'] = {'state': seed, 'inc': V.comm.Get_rank()}
        fgen.state = state
    rg_wrap = randomfunctiongen.Generator(fgen)

    if meth == 'beta':
        args = (0.3, 0.5)
    elif meth == 'binomial':
        args = (7, 0.3)
    elif meth == 'chisquare':
        args = (7,)
    elif meth == 'choice':
        args = (1234 * 5678,)
    elif meth == 'exponential':
        args = ()
    elif meth == 'f':
        args = (7, 17)
    elif meth == 'gamma':
        args = (3.14,)
    elif meth == 'geometric':
        args = (0.5,)
    elif meth == 'gumbel':
        args = ()
    elif meth == 'hypergeometric':
        args = (17, 2 * 17, 3 * 17 - 1)
    elif meth == 'laplace':
        args = ()
    elif meth == 'logistic':
        args = ()
    elif meth == 'lognormal':
        args = ()
    elif meth == 'logseries':
        args = (0.3,)
    elif meth == 'negative_binomial':
        args = (7, 0.3)
    elif meth == 'noncentral_chisquare':
        args = (7, 3.14)
    elif meth == 'noncentral_f':
        args = (7, 17, 3.14)
    elif meth == 'normal':
        args = ()
    elif meth == 'pareto':
        args = (3.14,)
    elif meth == 'poisson':
        args = ()
    elif meth == 'power':
        args = (3.14,)
    elif meth == 'random':
        args = ()
    elif meth == 'rayleigh':
        args = ()
    elif meth == 'standard_cauchy':
        args = ()
    elif meth == 'standard_exponential':
        args = ()
    elif meth == 'standard_gamma':
        args = (3.14,)
    elif meth == 'standard_normal':
        args = ()
    elif meth == 'standard_t':
        args = (7,)
    elif meth == 'triangular':
        args = (2.71, 3.14, 10.)
    elif meth == 'uniform':
        args = ()
    elif meth == 'vonmises':
        args = (2.71, 3.14)
    elif meth == 'wald':
        args = (2.71, 3.14)
    elif meth == 'weibull':
        args = (3.14,)
    elif meth == 'zipf':
        args = (3.14,)
    else:
        raise RuntimeError("Unknown method: add test for %s." % meth)

    for i in range(1, 10):
        f = getattr(rg_wrap, meth)(V, *args)
        with f.dat.vec_ro as v:
            if meth in ('rand', 'randn'):
                assert np.allclose(getattr(rg_base, meth)(v.local_size), v.array[:])
            else:
                kwargs = {'size': (v.local_size, )}
                assert np.allclose(getattr(rg_base, meth)(*args, **kwargs), v.array[:])
def test_randomgen_brng(brng, meth):

    seed = 123456789
    # Original
    bgen = getattr(randomgen, brng)(seed=seed)
    if brng == 'PCG64':
        state = bgen.state
        state['state'] = {'state': seed, 'inc': 0}
        bgen.state = state
    rg_base = randomgen.Generator(bgen)
    # Firedrake wrapper
    fgen = getattr(randomfunctiongen, brng)(seed=seed)
    if brng == 'PCG64':
        state = fgen.state
        state['state'] = {'state': seed, 'inc': 0}
        fgen.state = state
    rg_wrap = randomfunctiongen.Generator(fgen)

    if meth == 'beta':
        args = (0.3, 0.5)
        kwargs = {'size': 17}
    elif meth == 'binomial':
        args = (7, 0.3)
        kwargs = {'size': 17}
    elif meth == 'bytes':
        a0 = getattr(rg_base, meth)(17 + 1)
        a1 = getattr(rg_wrap, meth)(17 + 1)
        assert a0 == a1
        return
    elif meth == 'chisquare':
        args = (7, )
        kwargs = {'size': 17}
    elif meth == 'choice':
        args = (17, )
        kwargs = {'size': 17}
    elif meth == 'complex_normal':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'dirichlet':
        args = (np.arange(1, 17 + 1), )
        kwargs = {'size': 17}
    elif meth == 'exponential':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'f':
        args = (7, 17)
        kwargs = {'size': 17}
    elif meth == 'gamma':
        args = (3.14, )
        kwargs = {'size': 17}
    elif meth == 'geometric':
        args = (0.5, )
        kwargs = {'size': 17}
    elif meth == 'gumbel':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'hypergeometric':
        args = (17, 2 * 17, 3 * 17 - 1)
        kwargs = {'size': 17}
    elif meth == 'laplace':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'logistic':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'lognormal':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'logseries':
        args = (0.3, )
        kwargs = {'size': 17}
    elif meth == 'multinomial':
        args = (17, [0.1, 0.2, 0.3, 0.4])
        kwargs = {'size': 17}
    elif meth == 'multivariate_hypergeometric':
        args = ([16, 8, 4], 6)
        kwargs = {'size': 3}
    elif meth == 'multivariate_normal':
        args = ([3.14, 2.71], [[1.00, 0.01], [0.01, 2.00]])
        kwargs = {'size': 17}
    elif meth == 'negative_binomial':
        args = (7, 0.3)
        kwargs = {'size': 17}
    elif meth == 'noncentral_chisquare':
        args = (7, 3.14)
        kwargs = {'size': 17}
    elif meth == 'noncentral_f':
        args = (7, 17, 3.14)
        kwargs = {'size': 17}
    elif meth == 'normal':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'pareto':
        args = (3.14, )
        kwargs = {'size': 17}
    elif meth == 'permutation':
        args = (10 * 17, )
        kwargs = {}
    elif meth == 'poisson':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'power':
        args = (3.14, )
        kwargs = {'size': 17}
    elif meth == 'rand':
        args = (17, )
        kwargs = {}
    elif meth == 'random':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'rayleigh':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'shuffle':
        arr0 = np.arange(17 + 10)
        arr1 = np.arange(17 + 10)
        getattr(rg_base, meth)(arr0)
        getattr(rg_wrap, meth)(arr1)
        assert np.allclose(arr0, arr1)
        return
    elif meth == 'standard_cauchy':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'standard_exponential':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'standard_gamma':
        args = (3.14, )
        kwargs = {'size': 17}
    elif meth == 'standard_normal':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'standard_t':
        args = (7, )
        kwargs = {'size': 17}
    elif meth == 'tomaxint':
        args = (7, )
        kwargs = {}
    elif meth == 'triangular':
        args = (2.71, 3.14, 10.)
        kwargs = {'size': 17}
    elif meth == 'uniform':
        args = ()
        kwargs = {'size': 17}
    elif meth == 'vonmises':
        args = (2.71, 3.14)
        kwargs = {'size': 17}
    elif meth == 'wald':
        args = (2.71, 3.14)
        kwargs = {'size': 17}
    elif meth == 'weibull':
        args = (3.14, )
        kwargs = {'size': 17}
    elif meth == 'zipf':
        args = (3.14, )
        kwargs = {'size': 17}
    else:
        raise RuntimeError("Unknown method: add test for %s." % meth)

    for i in range(1, 10):
        assert np.allclose(
            getattr(rg_base, meth)(*args, **kwargs),
            getattr(rg_wrap, meth)(*args, **kwargs))
"""
The random module in NumPy provides several alternatives to the default PRNG,
which uses a 128-bit permutation congruential generator. While this is a good
general-purpose random number generator, it might not be sufficient some
particular needs. This module illustrates how to use other PSNG.
"""
from numpy import random

seed_seq = random.SeedSequence()
print(seed_seq)

bit_gen = random.MT19937(seed_seq)
rng = random.Generator(bit_gen)