コード例 #1
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})
コード例 #2
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})
コード例 #3
0
def xraysim(sourcelist, detectordeflist, scenegrid, scenematerials, materials,
            scene_resolution, detector_resolution):
    """ 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 bench.args.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
コード例 #4
0
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 31 14:14:15 2015

@author: Mads Thoudahl

"""
from xraysimphysics import emptyAAscene, addobjtoscene
from xraysimgeometry import coordsAAscene, raygeometry, detectorgeometry, runAABB
import numpy as np
from material import Material
from scene_objects import snake
from benchpress.benchmarks import util

bench = util.Benchmark("X-ray sim", "<screen-res>*<detector-res>*<iterations>")


class Const:
    EPS = 1e-5
    invsqr = 1.0 / (np.pi * 4)


def buildscene(
    scenedefs,  # scenedefinitions
    objlist,  # list of objects, obj=
    verbose=False  # printing status updates along the way
):
    """ Builds and returns a (sparse) scenegrid, and a (dense) voxel array,
        describing what materials are in which voxels
コード例 #5
0
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("LU decomposition on the matrix so that A = L*U",
                       "<size>")


def lu(a):
    """
    Perform LU decomposition on the matrix `a` so that A = L*U
    """
    u = a.copy()
    l = np.identity(a.shape[0], a.dtype)
    for c in range(1, u.shape[0]):
        l[c:, c - 1] = (u[c:, c - 1] / u[c - 1, c - 1:c])
        u[c:,
          c - 1:] = u[c:, c - 1:] - l[c:, c - 1][:, None] * u[c - 1, c - 1:]
        bench.flush()
    return (l, u)


def main():
    n = bench.args.size[0]
    matrix = bench.random_array((n, n))
    bench.start()
    res = lu(matrix)
    bench.stop()
    bench.pprint()

コード例 #6
0
from __future__ import print_function
"""
The Lattice Boltzmann Methods D2Q9
------------

Channel flow past a cylindrical obstacle, using a LB method
Copyright (C) 2006 Jonas Latt
Address: Rue General Dufour 24,  1211 Geneva 4, Switzerland
E-mail: [email protected]
"""
import numpy as np
from benchpress.benchmarks import util

bench = util.Benchmark("The Lattice Boltzmann Methods D2Q9",
                       "height*width*iterations")

# D2Q9 Lattice constants
t = [
    4 / 9., 1 / 9., 1 / 9., 1 / 9., 1 / 9., 1 / 36., 1 / 36., 1 / 36., 1 / 36.
]
cx = [0, 1, 0, -1, 0, 1, -1, -1, 1]
cy = [0, 0, 1, 0, -1, 1, 1, -1, -1]
opp = [0, 3, 4, 1, 2, 7, 8, 5, 6]
uMax = 0.02  # maximum velocity of Poiseuille inflow
Re = 100  # Reynolds number


def cylinder(height, width, obstacle=True):
    assert (height > 2)
    assert (width > 2)
コード例 #7
0
from __future__ import print_function
from benchpress.benchmarks import util

# if Bohrium is installed we use its convolve else we use the convolve from SciPy
try:
    raise ImportError
    import bohrium as bh
    convolveNd = bh.convolve_scipy
except ImportError:
    import scipy
    from scipy import signal
    convolveNd = signal.convolve

bench = util.Benchmark("Convolution Filter (any dimensional)", "<image-size>*<filter-size>*<ndims>*<niters>")


def main():
    """
    Convolve filter (any dimensional)
    Parameter: `<image-size>*<filter-size>*<ndims>*<niters>`
                where image and filter size is the size of each dimension (not their total size).
    """
    (image_size, filter_size, ndims, I) = bench.args.size

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

    bench.start()
    for _ in range(I):
        R = convolveNd(image, image_filter)
        bench.flush()
コード例 #8
0
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Leibnitz Pi", "<size>*<niters>")


def leibnitz_pi(N):
    n = np.arange(0, N)
    return np.sum(1.0 / (4 * n + 1) - 1.0 / (4 * n + 3))


def main():
    (size, niter) = bench.args.size

    bench.start()
    pi = 0.0
    for _ in range(niter):
        pi += 4.0 * leibnitz_pi(size)  # Execute benchmark
        bench.flush()
    pi /= niter
    bench.stop()
    bench.pprint()
    if bench.args.verbose:
        print(pi)


if __name__ == "__main__":
    main()
コード例 #9
0
# This Python file uses the following encoding: utf-8
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np
import math

bench = util.Benchmark("Magnetic Field Extrapolation", "<x-size>*<y-size>*<iterations>")


def window(B, a=0.37):
    assert (len(B.shape) == 2)
    assert (B.shape[0] == B.shape[1])
    n = B.shape[0]
    wl = np.ones_like(B[0])
    b = int(np.ceil((a * (n - 1) / 2)))
    wl[:b] = 0.5 * (1 + np.cos(math.pi * (2 * np.arange(b) / (a * (n - 1)) - 1)))
    wl[-b:] = 0.5 * (1 + np.cos(math.pi * (2 * np.arange(b - 1, -1, -1) / (a * (n - 1)) - 1)))
    wl *= wl
    w = np.sqrt(wl + wl[:, None])
    return B * w


def calcB(B_x0, alpha=0.0,
          x_min=0.0, x_max=0.25,
          y_min=0.0, y_max=1.0,
          z_min=0.0, z_max=1.0):
    n = len(B_x0)
    x = np.linspace(x_min, x_max, num=n, endpoint=False).astype(B_x0.dtype, copy=False)
    y = np.linspace(y_min, y_max, num=n).astype(B_x0.dtype, copy=False)
    z = np.linspace(z_min, z_max, num=n).astype(B_x0.dtype, copy=False)
    u = np.arange(n, dtype=B_x0.dtype)
コード例 #10
0
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Monte Carlo Pi", "samples*iterations")


def montecarlo_pi(samples):
    x = bench.random_array((samples,))
    y = bench.random_array((samples,))
    m = np.sqrt(x * x + y * y) <= 1.0
    return np.sum(m) * 4.0 / samples


def solve(samples, iterations):
    acc = 0.0
    for _ in range(iterations):
        acc += montecarlo_pi(samples)
        bench.flush()
    acc /= iterations
    return acc


def main():
    samples, iterations = bench.args.size
    bench.start()
    res = solve(samples, iterations)
    bench.stop()
    bench.pprint()
    if bench.args.verbose:
        print(res)
コード例 #11
0
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Galton Bean Machine", "<num_of_beans>*<height>")


def bean(num_beans, height):
    return np.sum(np.sign(bench.random_array((num_beans, height)) - 0.5),
                  axis=1)


def main():
    num_beans, height = bench.args.size

    bench.start()
    R = bean(num_beans, height)
    bench.stop()
    bench.save_data({'res': R})
    bench.pprint()

    if bench.args.visualize:
        from matplotlib import pyplot
        bins = 100
        pyplot.hist(R, bins)
        pyplot.title("Galton Normal distribution")
        pyplot.xlabel("Value")
        pyplot.ylabel("Frequency")
        pyplot.show()

コード例 #12
0
# -*- coding: utf-8 -*-
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Quasi Crystal simulation",
                       "k*stripes*image_size*iterations")


def main():
    k = bench.args.size[0]  # number of plane waves
    stripes = bench.args.size[1]  # number of stripes per wave
    N = bench.args.size[2]  # image size in pixels
    ite = bench.args.size[3]  # iterations

    phases = np.arange(0, 2 * np.pi, 2 * np.pi / ite)
    image = np.empty((N, N), dtype=bench.dtype)
    d = np.arange(-N / 2, N / 2, dtype=bench.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)
コード例 #13
0
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Rosenbrock", "size*iterations")


def rosen(x):
    return np.sum(
        100.0 * (x[1:] - x[:-1] ** 2.0) ** 2.0 + \
        (1 - x[:-1]) ** 2.0
    )


def main():
    N, T = bench.args.size  # Grab command-line arguments
    dataset = np.arange(N, dtype=bench.dtype) / bench.dtype(N)

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


if __name__ == "__main__":
    main()
コード例 #14
0
from __future__ import print_function
"""
Shallow Water
-------------

So what does this code example illustrate?

Adapted from: http://people.sc.fsu.edu/~jburkardt/m_src/shallow_water_2d/
"""
import numpy as np
from benchpress.benchmarks import util

bench = util.Benchmark("Shallow Water", "height*width*iterations")
g = 9.80665  # gravitational acceleration


def droplet(height, width, data_type=np.float32):
    """Generate grid of droplets"""

    x = np.array(np.linspace(-1, 1, num=width, endpoint=True), dtype=data_type)
    y = np.array(np.linspace(-1, 1, num=width, endpoint=True), dtype=data_type)
    (xx, yy) = np.meshgrid(x, y)
    droplet = height * np.exp(-5 * (xx**2 + yy**2))
    return droplet


def model(height, width, dtype=np.float32):
    assert height >= 16
    assert width >= 16
    m = np.ones((height, width), dtype=dtype)
    D = droplet(8, 8)  # simulate a water drop
コード例 #15
0
from __future__ import print_function
"""
Game of Life
------------

"""
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Game of Life", "height*width*iterations*rules")

SURVIVE_LOW = 2
SURVIVE_HIGH = 3
SPAWN = 3


def world(height, width):
    state = np.ones((height + 2, width + 2), dtype=bench.dtype)
    state[2:-2, 2:-2] = bench.dtype(0)
    return state


def world_zeros(height, width):
    state = np.zeros((height + 2, width + 2), dtype=bench.dtype)
    return state


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]
コード例 #16
0
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 20 10:47:25 2014
GPL

@author: Rasmus Nordfang
"""

from benchpress.benchmarks import util
import numpy as np
from salt import salt
from temp import temp
from density_imr import dens
from heat_imr import heatcap

bench = util.Benchmark("Wisp", "length*width*steps")

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

N_L = bench.args.size[0]  # number of grids in Length direction
N_W = bench.args.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
コード例 #17
0
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np
import math

try:
    import numpy_force as npf
except ImportError:
    import numpy as npf

bench = util.Benchmark("Black Scholes", "samples*iterations")


def model(N):
    """Construct pseudo-data representing price samples?"""
    # Create the outside of bohrium
    S = npf.random.random(N).astype(
        bench.dtype) * 4.0 + 58.0  # Price is between 58-62
    S = np.array(S)
    return S


def CND(X):
    """
    Cumulative normal distribution.
    Helper function used by BS(...).
    """

    (a1, a2, a3, a4, a5) = (0.31938153, -0.356563782, 1.781477937,
                            -1.821255978, 1.330274429)
    L = np.absolute(X)
コード例 #18
0
from __future__ import print_function
import cupy as np
from benchpress.benchmarks import util

bench = util.Benchmark("Solving the heat equation using the jacobi method",
                       "height*width*iterations")


def init_grid(height, width, dtype=np.float32):
    grid = np.zeros((height + 2, width + 2), dtype=dtype)
    grid[:, 0] = dtype(-273.15)
    grid[:, -1] = dtype(-273.15)
    grid[-1, :] = dtype(-273.15)
    grid[0, :] = dtype(40.0)
    return grid


def jacobi(grid, epsilon=0.005, max_iterations=None):
    def loop_body(grid):
        center = grid[1:-1, 1:-1]
        north = grid[0:-2, 1:-1]
        east = grid[1:-1, 2:]
        west = grid[1:-1, 0:-2]
        south = grid[2:, 1:-1]
        work = 0.2 * (center + north + east + west + south)
        delta = np.sum(np.absolute(work - center))
        center[:] = work
        bench.plot_surface(grid, "2d", 0, 200, -200)
        return delta > epsilon

    bench.do_while(loop_body, max_iterations, grid)
コード例 #19
0
# By  Natalino Busa <https://gist.github.com/natalinobusa/4633275>
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Snakes and Ladders", "size*iterations")


def nullgame(size, dtype):
    p = np.zeros((size + 1, size + 1), dtype=dtype)

    for i in range(size + 1):
        for j in range(6):
            if i + j < size:
                p[i][i + j + 1] = 1.0 / 6.0

    p[size][size] = 1
    p[size - 1][size] = 6.0 / 6.0
    p[size - 2][size] = 5.0 / 6.0
    p[size - 3][size] = 4.0 / 6.0
    p[size - 4][size] = 3.0 / 6.0
    p[size - 5][size] = 2.0 / 6.0
    p[size - 6][size] = 1.0 / 6.0
    return p


def main():
    size, iterations = bench.args.size

    if bench.args.visualize:
        from matplotlib import pyplot
コード例 #20
0
"""
Convolve filter (1. dimensional)
Parameter: `--size<image-size>*<filter-size>*<niters>`.
"""

from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Convolution Filter 1D", "<image-size>*<filter-size>*<niters>")


def main():
    (image_size, filter_size, I) = bench.args.size

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

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


if __name__ == "__main__":
    main()
コード例 #21
0
ファイル: gauss.py プロジェクト: Shadesfear/benchpress
from __future__ import print_function
from benchpress.benchmarks import util
import numpy as np

bench = util.Benchmark("Gaussian elimination on matrix a without pivoting",
                       "<size>")


def gauss(a):
    """
    Perform Gaussian elimination on matrix a without pivoting
    """
    for c in range(1, a.shape[0]):
        a[c:, c -
          1:] = a[c:, c - 1:] - (a[c:, c - 1] /
                                 a[c - 1, c - 1:c])[:, None] * a[c - 1, c - 1:]
        bench.flush()
    a /= np.diagonal(a)[:, None]
    return a


def main():
    n = bench.args.size[0]

    matrix = bench.load_data()
    if matrix is not None:
        matrix = matrix['matrix']
    else:
        matrix = bench.random_array((n, n))

    bench.start()