def main():
    B = util.Benchmark()
    H = B.size[0]
    W = B.size[1]

    A1 = B.random_array((H, W))
    A2 = B.random_array((H, W))
    A3 = B.random_array((H, W))
    A4 = B.random_array((H, W))

    B.start()

    R = solve_tridiag(A1, A2, A3, A4, B)

    if util.Benchmark().bohrium:
        R.copy2numpy()

    B.stop()

    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})

    if B.verbose:
        print(R)
Пример #2
0
def main():
    B = util.Benchmark()  # Initialize Benchpress
    N, T = B.size  # Grab command-line arguments

    if B.inputfn:
        dataset = B.load_array()
    else:
        dataset = np.arange(N, dtype=B.dtype) / B.dtype(
            N)  # Create psuedo-data

    if B.dumpinput:
        B.dump_arrays("rosenbrock", {'input': dataset})

    B.start()  # Sample wall-clock start
    res = 0.0
    for _ in range(0, T):  # Do T trials of..
        res += rosen(dataset)  # ..executing rosenbrock.
        util.Benchmark().flush()
    res /= T
    B.stop()  # Sample wall-clock stop
    B.pprint()  # Print elapsed wall-clock etc.

    R = np.zeros((1), dtype=B.dtype)
    R[0] = res
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})

    if B.verbose:  # Print more, such as results
        print(R)
def main():
    B = util.Benchmark()
    N = B.size[0]

    if B.inputfn:
        S = B.load_array()
    else:
        S = B.random_array((N, N))

    if B.dumpinput:
        B.dump_arrays("gauss", {'input':S})

    B.start()

    for c in range(1, S.shape[0]):
        S[c:, c - 1:] -= (S[c:,c-1:c] / S[c-1:c,c-1:c]) * S[c-1:c,c-1:]
        B.flush()

    S /= np.diagonal(S)[:, None]

    R = S
    if util.Benchmark().bohrium:
        R.copy2numpy()

    B.stop()

    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})

    if B.verbose:
        print (R)
Пример #4
0
def main():
    B = util.Benchmark()

    k       = B.size[0] # number of plane waves
    stripes = B.size[1] # number of stripes per wave
    N       = B.size[2] # image size in pixels
    ite     = B.size[3] # iterations

    phases  = np.arange(0, 2*np.pi, 2*np.pi/ite)
    image   = np.empty((N, N), dtype=B.dtype)
    d       = np.arange(-N/2, N/2, dtype=B.dtype)

    xv, yv = np.meshgrid(d, d)
    theta  = np.arctan2(yv, xv)
    r      = np.log(np.sqrt(xv*xv + yv*yv))
    r[np.isinf(r) == True] = 0

    tcos   = theta * np.cos(np.arange(0, np.pi, np.pi/k))[:, np.newaxis, np.newaxis]
    rsin   = r * np.sin(np.arange(0, np.pi, np.pi/k))[:, np.newaxis, np.newaxis]
    inner  = (tcos - rsin) * stripes

    cinner = np.cos(inner)
    sinner = np.sin(inner)

    B.start()

    for phase in phases:
        image[:] = np.sum(cinner * np.cos(phase) - sinner * np.sin(phase), axis=0) + k
        util.Benchmark().flush()

    B.stop()
    B.pprint()

    if B.outputfn:
        B.tofile(B.outputfn, {'res': image})
Пример #5
0
def main():
    B = util.Benchmark()
    N = B.size[0]

    if B.inputfn:
        S = B.load_array()
    else:
        S = B.random_array((N, N))

    if B.dumpinput:
        B.dump_arrays("gauss", {'input': S})

    B.start()
    R = la.gauss(S)

    if util.Benchmark().bohrium:
        R.copy2numpy()

    B.stop()

    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})

    if B.verbose:
        print(R)
Пример #6
0
def main():
    B = util.Benchmark()  # Initialize Benchpress
    nplanets, nbodies, timesteps = B.size  # Grab arguments

    x_max = 1e18  # Simulation constants
    y_max = 1e18
    z_max = 1e18
    dt = 1e12

    solarsystem, asteroids = random_system(  # Setup galaxy
        x_max, y_max, z_max, nplanets, nbodies, B.dtype)

    if B.visualize:  # Init visuals
        plt, P3 = gfx_init(x_max, y_max, z_max)

    B.start()  # Timer start
    for timestep in range(0, timesteps):  # Run simulation
        if B.visualize and timestep % 10 == 0:  # With or without..
            gfx_show(plt, P3, solarsystem, asteroids)  # ..visuals
        move(solarsystem, asteroids, dt)
        util.Benchmark().flush()
    B.stop()  # Timer stop

    B.pprint()  # Print results..
    if B.verbose:  # ..and more.
        print(R)
    if B.visualize:  # Keep showing visuals
        plt.show(block=True)
Пример #7
0
def solve(samples, iterations, B):
    acc = 0.0
    for _ in range(iterations):
        acc += montecarlo_pi(samples, B)
        util.Benchmark().flush()
    acc /= iterations
    return acc
Пример #8
0
def main():
    B = util.Benchmark()
    if B.inputfn is None:
        B_x0 = B.random_array((B.size[0], B.size[1]), dtype=B.dtype)
    else:
        inputfn = B.inputfn if B.inputfn else '../idl_input-float64_512*512.npz'
        sd = {512: 1, 256: 2, 128: 4, 64: 8, 32: 16, 16: 32, 8: 64}
        try:
            h = sd[B.size[0]]
            w = sd[B.size[1]]
        except KeyError:
            raise ValueError('Only valid sizes are: ' + str(sd.keys()))
        B_x0 = B.load_array(inputfn, 'input', dtype=B.dtype)[::h, ::w]

    B.start()
    for _ in range(B.size[2]):
        Rx, Ry, Rz = calcB_numba(window(B_x0.copy()))
        """
        Rx1, Ry1, Rz1 = calcB_loop(window(B_x0.copy()))
        assert np.allclose(Rx, Rx1)
        assert np.allclose(Ry, Ry1)
        assert np.allclose(Rz, Rz1)
        """
    B.stop()
    B.pprint()

    if B.outputfn:
        R = Rx + Ry + Rz
        B.tofile(B.outputfn, {'res': R, 'res_x': Rx, 'res_y': Ry, 'res_z': Rz})
Пример #9
0
def main():

    B = util.Benchmark()
    (H, W, I, V) = B.size

    if V not in [1, 2]:
        raise Exception("Unsupported rule-implementation.")
    if B.inputfn:
        if "LIF" in B.inputfn:
            paths = pattern_paths("cells")
            S = world_zeros(H, W, B)
            cells = cells_from_file(B.inputfn)
            insert_cells(S, cells)
        else:
            S = B.load_array()
    else:
        S = world(H, W, B)

    B.start()
    R = play(S, I, V, B.visualize)
    B.stop()

    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})
    if B.visualize:
        util.confirm_exit()
Пример #10
0
def main():
    B = util.Benchmark()
    num_asteroids = B.size[0]
    num_planets = B.size[1]
    num_iteratinos = B.size[2]

    x_max = 1e18
    y_max = 1e18
    z_max = 1e18
    dt = 1e12

    solarsystem, astoroids = random_system(x_max, y_max, z_max, num_planets,
                                           num_asteroids, B)
    if B.verbose:
        P3 = gfx_init(x_max, y_max, z_max)
    B.start()
    for _ in range(num_iteratinos):
        move(solarsystem, astoroids, dt)
        if B.verbose:
            show(P3, solarsystem, astoroids)
    R = solarsystem['x']
    B.stop()
    B.pprint()
    if B.verbose:
        print(R)
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})
def main():
    B = util.Benchmark()

    fig = plt.figure()
    plt.xticks([])
    plt.yticks([])

    k = B.size[0]  # number of plane waves
    stripes = B.size[1]  # number of stripes per wave
    N = B.size[2]  # image size in pixels
    ite = B.size[3]  # iterations

    phases = np.array([i * (2 * np.pi / (ite)) for i in range(ite)])

    image = np.empty((N, N), dtype=B.dtype)
    d = np.arange(-N / 2, N / 2, dtype=B.dtype)

    xv, yv = np.meshgrid(d, d)
    theta = np.arctan2(yv, xv)
    r = np.log(np.sqrt(xv * xv + yv * yv))
    r[np.isinf(r) == True] = 0

    arr = np.array([i * np.pi / k for i in range(k)])
    tcos = theta * np.cos(arr)[:, np.newaxis, np.newaxis]
    rsin = r * np.sin(arr)[:, np.newaxis, np.newaxis]

    inner = (tcos - rsin) * stripes

    cinner = np.cos(inner)
    sinner = np.sin(inner)

    B.start()

    for phase in phases:
        image[:] = np.sum(cinner * np.cos(phase) - sinner * np.sin(phase),
                          axis=0) + k
        util.Benchmark().flush()

    B.stop()
    B.pprint()

    if B.outputfn:
        B.tofile(B.outputfn, {'res': image})

    if B.verbose:
        print(image)
Пример #12
0
def main():
    B = util.Benchmark()
    samples, iterations = B.size
    B.start()
    R = solve(samples, iterations, B)
    B.stop()
    B.pprint()
    if B.verbose:
        print(R)
Пример #13
0
def simulate(galaxy, timesteps, visualize=False):
    for i in range(timesteps):
        move(galaxy, dt)
        util.Benchmark().flush()
        if visualize:  #NB: this is only for experiments
            T = np.zeros((3, len(galaxy['x'])), dtype=np.float32)
            T[0, :] = galaxy['x']
            T[1, :] = galaxy['y']
            T[2, :] = galaxy['z']
            np.visualize(T, "3d", 0, 0.0, 10)
Пример #14
0
def main():
    B = util.Benchmark()
    scene_res = B.size[0]
    detector_res = B.size[1]
    iterations = B.size[2]
    scene = setup(scene_res, detector_res)

    B.start()
    for _ in range(iterations):
        detector_results = xraysim(*scene, visualize=B.visualize)
        if util.Benchmark().bohrium:
            B.flush()

    B.stop()
    B.pprint()

    if B.outputfn:
        B.tofile(B.outputfn, {'res': detector_results[0]})

    if B.visualize:
        util.confirm_exit()
Пример #15
0
def main():
    B = util.Benchmark()
    N = B.size[0]
    I = B.size[1]

    if B.inputfn:
        galaxy = B.load_arrays(B.inputfn)
    else:
        galaxy = random_galaxy(N, B, B.dtype)
        util.Benchmark().flush()

    if B.dumpinput:
        B.dump_arrays("nbody", galaxy)

    B.start()
    simulate(galaxy, I, visualize=B.visualize)
    R = galaxy['x'] + galaxy['y'] + galaxy['z']
    B.stop()

    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})
Пример #16
0
def main():
    B = util.Benchmark()
    N = B.size[0]

    if B.inputfn:
        a = B.load_array()
    else:
        a = B.random_array((N, N), dtype=B.dtype)

    if B.dumpinput:
        B.dump_arrays("lu", {'input': a})

    B.start()
    (l, u) = la.lu(a)
    if util.Benchmark().bohrium:
        l.copy2numpy()
        u.copy2numpy()
    B.stop()

    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': u})
    if B.verbose:
        print(u)
Пример #17
0
def main():
    B = util.Benchmark()  # Initialize Benchpress
    try:
        N, I = B.size  # Grab command-line arguments
    except ValueError:
        N, I = (B.size[0], 1)
    B.start()  # Sample wall-clock start
    R = 0.0
    for _ in range(I):
        R += 4.0 * leibnitz_pi(N)  # Execute benchmark
        B.flush()
    B.stop()  # Sample wall-clock stop
    B.pprint()  # Print elapsed wall-clock etc.
    if B.verbose:  # Print more, such as results
        print(R)
Пример #18
0
def play(state, iterations, version=1, visualize=False):

    cells = state[1:-1, 1:-1]
    ul = state[0:-2, 0:-2]
    um = state[0:-2, 1:-1]
    ur = state[0:-2, 2:]
    ml = state[1:-1, 0:-2]
    mr = state[1:-1, 2:]
    ll = state[2:, 0:-2]
    lm = state[2:, 1:-1]
    lr = state[2:, 2:]

    def update():
        """
        This is the first implementation of the game rules.
        """
        neighbors = ul + um + ur + ml + mr + ll + lm + lr  # count neighbors
        live = neighbors * cells  # extract live cells neighbors
        stay = (live >= SURVIVE_LOW) & (live <= SURVIVE_HIGH
                                        )  # find cells the stay alive
        dead = neighbors * (cells == 0)  # extract dead cell neighbors
        spawn = dead == SPAWN  # find cells that spaw new life

        cells[:] = stay | spawn  # save result for next iteration

    def update_optimized():
        """
        This is an optimized implementation of the game rules.
        """
        neighbors = ul + um + ur + ml + mr + ll + lm + lr  # Count neighbors

        c1 = (neighbors == SURVIVE_LOW)  # Life conditions
        c2 = (neighbors == SPAWN)

        cells[:] = cells * c1 + c2  # Update

    if version == 1:  # Select the update function
        update_func = update
    elif version == 2:
        update_func = update_optimized

    for i in range(iterations):  # Run the game
        if visualize:
            util.plot_surface(state, "3d", 16, 1, 0)
        update_func()
        util.Benchmark().flush()

    return state
def main():
    B = util.Benchmark()
    H = B.size[0]
    W = B.size[1]
    I = B.size[2]
    state = B.load_data()
    if state is None:
        state = cylinder(H, W)
    B.start()
    solve(B, state, I, B.visualize)
    B.stop()
    B.save_data(state)
    B.pprint()
    if B.verbose:
        print("Iterations=%s, State: %s." % (I, state))
    if B.visualize:
        util.confirm_exit()
Пример #20
0
def main():
    B = util.Benchmark()
    (image_size, filter_size, I) = B.size

    image = B.random_array((image_size,))
    image_filter = B.random_array((filter_size,))

    B.start()
    for _ in range(I):
        R = np.convolve(image, image_filter)
        B.flush()
    B.stop()
    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})

    if B.verbose:
        print (R)
Пример #21
0
def main():
    B = util.Benchmark()
    H = B.size[0]
    W = B.size[1]
    I = B.size[2]

    state = B.load_data()
    if state is None:
        state = model(H, W, dtype=B.dtype)

    B.start()
    simulate(B, state, I, visualize=B.visualize)
    B.stop()
    B.save_data(state)
    B.pprint()
    if B.verbose:
        print("Iterations=%s, State: %s." % (I, state))
    if B.visualize:
        util.confirm_exit()
Пример #22
0
def wireworld(world, iterations):
    """TODO: Describe the benchmark."""

    sim = no_border(world, 1)  # Active Machine
    stencil = D2P8(world)  # Stencil for counting heads
    NC = sum([v == 2 for v in stencil])  # Count number of head neighbors
    for _ in range(iterations):
        # Mask conductor->head
        MASK = ((NC == 1) & (sim == 8)) | ((NC == 2) & (sim == 8))

        sim *= ~MASK  # New head pos->0
        sim += np.array(MASK * 1, np.uint8)  # New head pos->1
        MASK = (sim == 8)  # Mask non conductors
        sim *= ~MASK  # conductors->0
        sim += np.array(MASK * 4, np.uint8)  # conductors->4
        sim *= 2  # Upgrade all to new state

        util.Benchmark().flush()

    return sim
Пример #23
0
def main():
    B = util.Benchmark()
    H = B.size[0]
    W = B.size[1]
    I = B.size[2]

    grid = B.load_data()
    if grid is not None:
        grid = grid['grid']
    else:
        grid = init_grid(H, W, dtype=B.dtype)

    B.start()
    grid = jacobi(B, grid, max_iterations=I, visualize=B.visualize)
    B.stop()
    B.save_data({'grid': grid})
    B.pprint()
    if B.verbose:
        print("Iterations=%s, Grid: %s." % (I, grid))
    if B.visualize:
        util.confirm_exit()
Пример #24
0
def main():
    B = util.Benchmark()
    num_beans, height = B.size

    B.start()
    R = bean(B, num_beans, height)
    B.stop()

    B.pprint()
    if B.verbose:
        print(R)
    if B.visualize:
        from matplotlib import pyplot
        bins   = 100
        pyplot.hist(R, bins)
        pyplot.title("Galton Normal distribution")
        pyplot.xlabel("Value")
        pyplot.ylabel("Frequency")
        pyplot.show()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})
Пример #25
0
def main():
    """
    Example parameter: --size=100*10.
    This will execute on a 1000x1000 dataset for 10 iterations.
    """
    B = util.Benchmark()
    (N, I) = B.size
    if B.inputfn:
        world = B.load_array()
    else:
        world = wireworld_init(N)

    if B.dumpinput:
        B.dump_arrays("wireworld", {"input": world})

    B.start()
    R = wireworld(world, I)
    B.stop()
    B.pprint()

    if B.outputfn:
        B.tofile(B.outputfn, {"res": R})
Пример #26
0
def main():
    B = util.Benchmark()
    H = B.size[0]
    W = B.size[1]
    I = B.size[2]

    state = cylinder(H, W, obstacle=False)

    viz = None
    if B.verbose:
        viz = setup_viz(state)

    B.start()
    if viz:
        thread = threading.Thread(target=solve, args=(state, I, B, viz))
        thread.start()
        viz['tk'].mainloop()
    else:
        R = solve(state, I, B, viz)
    B.stop()
    B.pprint()

    if B.outputfn:
        B.tofile(B.outputfn, {'res': np.array(R)})
Пример #27
0
def main():
    """
    Convolve filter (any dimensional)
    Parameter: `--size<image-size>*<filter-size>*<ndims>*<niters>`
                where image and filter size is the size of each dimension (not their total size).
    """
    B = util.Benchmark()
    (image_size, filter_size, ndims, I) = B.size

    image = B.random_array((image_size**ndims, )).reshape([image_size] * ndims)
    image_filter = B.random_array(
        (filter_size**ndims, )).reshape([filter_size] * ndims)

    B.start()
    for _ in range(I):
        R = bh.convolve_scipy(image, image_filter)
        B.flush()
    B.stop()
    B.pprint()
    if B.outputfn:
        B.tofile(B.outputfn, {'res': R})

    if B.verbose:
        print(R)
Пример #28
0
def xraysim(sourcelist,
            detectordeflist,
            scenegrid,
            scenematerials,
            materials,
            scene_resolution,
            detector_resolution,
            verbose=False,
            visualize=False):
    """ performs the calculations figuring out what is detected
        INPUT:
        sourcelist: list of np.array([
                        px,py,pz,       position
                        relative_power, relative to other sources simulated
                        energy])        MeV

        detectorlist: list of np.array([
                        px0,py0,pz0,    position lower left corner
                        px1,py1,pz1,    position upper right corner
                        res1,res2 ])    resolution of detector

        scenegrid:      a numpy array 'meshgrid' shaped (xs+1,ys+1,zs+1)
                        containing absolute coordinates of grid at 'intersections'
                        as returned by buildscene

        scenematerials: a numpy array shaped (xs,ys,zs)
                        containing information of which MATERIAL inhibits
                        any voxel, as an integer value.
                        ## for a better model this should also contain
                        ## information of how much of the voxel is filled..

        materials:     a dict containing all materials used in the scenematerials
                       as Material objects

        scene_resolution:    resolution of the scene cubic, e.g. 32 equals 32^3

        detector_resolution: resolution of the detectors squared, e.g. 22 equals 22^2
    """
    ## indexing constants
    power = 3

    # generate an array of endpoints for rays (at the detector)
    detectors = []
    for ddef in detectordeflist:
        detectors.append(detectorgeometry(ddef))

    for source in sourcelist:
        # unpack source
        sx, sy, sz, spower, senergy = source
        rayorigin = sx, sy, sz

        # preprocess the scene physics
        # building a map of attenuation coefficients
        sceneattenuates = np.zeros(scenematerials.shape)

        for material_id in materials.keys():
            sceneattenuates += (scenematerials == material_id) \
                    * materials[material_id].getMu(senergy)

        ret = []
        for pixelpositions, pixelareavector, dshape, result in detectors:
            # do geometry
            rayudirs, raylengths, rayinverse = raygeometry(
                rayorigin, pixelpositions)
            raydst = runAABB(scenegrid, rayudirs, rayorigin, rayinverse)

            #raydst is now to be correlated with material/attenuation grid
            t = sceneattenuates[..., np.newaxis] * raydst
            #We sums the three dimensions
            t = np.sum(t, axis=(0, 1, 2))
            dtectattenuates = t.reshape(detector_resolution,
                                        detector_resolution)
            pixelintensity = ((Const.invsqr * source[power] *
                               np.ones(raylengths.shape[0])[..., np.newaxis]) /
                              raylengths).reshape(dshape)
            area = np.dot(rayudirs, pixelareavector.reshape(3,
                                                            1)).reshape(dshape)
            result += pixelintensity * area * np.exp(-dtectattenuates)
            ret.append(result)
            if visualize:
                low = np.minimum.reduce(result.flatten())
                high = np.maximum.reduce(result.flatten())
                if util.Benchmark().bohrium:
                    low = low.copy2numpy()
                    high = high.copy2numpy()
                util.plot_surface(result, "2d", 0, low - 0.001 * low,
                                  high - 0.5 * high)
                util.plot_surface(result, "2d", 0, low - 0.001 * low,
                                  high - 0.5 * high)

    #We return only the result of the detectors
    return ret
Пример #29
0
def main():

    B = util.Benchmark()
    size = B.size[0]
    iterations = B.size[1]

    if B.visualize:
        from matplotlib import pyplot

    if B.inputfn:
        arrays = B.load_arrays(B.inputfn)
        a = arrays['a']
        p = arrays['p']
    else:
        a = np.array(np.zeros(size + 1, dtype=B.dtype))
        p = np.array(nullgame(size, dtype=B.dtype))

    if B.dumpinput:
        B.dump_arrays("snakes_and_ladders", {"a": a, "p": p})

    m = p  # Initial matrix is p
    pr_end = np.array(np.zeros(iterations, dtype=B.dtype))

    B.start()
    for k in range(iterations):
        if B.visualize:
            # Plot the probability distribution at the k-th iteration
            pyplot.figure(1)
            pyplot.plot(m[0][0:size])

        # Store the probability of ending after the k-th iteration
        pr_end[k] = m[0][size]

        # Store/plot the accumulated marginal probability at the k-th iteration
        a = a + m[0]

        util.Benchmark().flush()

        if B.visualize:
            pyplot.figure(2)
            pyplot.plot(a[0:size])

        #calculate the stocastic matrix for iteration k+1
        if B.bohrium and B.no_extmethods:
            m = np.array(np.dot(m.copy2numpy(), p.copy2numpy()))
        else:
            m = np.dot(m, p)

    B.stop()
    B.pprint()

    #plot the probability of ending the game
    # after k iterations
    if B.visualize:
        pyplot.figure(3)
        pyplot.plot(pr_end[0:iterations - 1])

        #show the three graphs
        pyplot.show()

    if B.verbose:
        print(pr_end)

    if B.outputfn:
        B.tofile(B.outputfn, {'res': pr_end})
Пример #30
0
GPL

@author: Rasmus Nordfang
"""

from benchpress import util
import numpy as np

import time as tid

from salt import salt
from temp import temp
from density_imr import dens
from heat_imr import heatcap

B = util.Benchmark()

length = 1  #size of the grid unit m
width = 1  #size of the grid unit m

N_L = B.size[0]  #number of grids in Length direction
N_W = B.size[1]  #number of grids in width direction

n_years = 10  #number of years
#parameters

#Generel Start Values
#temp,[C]     density[kg/m^3],  depth,[m]      mass[kg]        Salinity[g/kg]
T_ML = -4
p_ML = 10
h_ML = 50