def backend(request): backend, lazy = request.param # Initialise the backend try: op2.init(backend=backend, lazy_evaluation=(lazy == 'lazy')) # Skip test if initialisation failed except: pytest.skip('Backend %s is not available' % backend) return backend
def _init(): """Cause :func:`pyop2.init` to be called in case the user has not done it for themselves. The result of this is that the user need only call :func:`pyop2.init` if she wants to set a non-default option, for example to switch the backend or the debug or log level.""" from pyop2 import op2 from firedrake.parameters import parameters if not op2.initialised(): op2.init(**parameters["pyop2_options"])
def backend(request): # Initialise the backend try: op2.init(backend=request.param) # Skip test if initialisation failed except: pytest.skip('Backend %s is not available' % request.param) request.addfinalizer(op2.exit) return request.param
def _init(): """Cause :func:`pyop2.init` to be called in case the user has not done it for themselves. The result of this is that the user need only call :func:`pyop2.init` if she wants to set a non-default option, for example to switch the backend or the debug or log level.""" from pyop2 import op2 from parameters import parameters if not op2.initialised(): op2.init(log_level="INFO", compiler=parameters["coffee"]["compiler"], simd_isa=parameters["coffee"]["simd_isa"])
def test_invalid_init(self): "init should not accept an invalid backend." with pytest.raises(ImportError): op2.init(backend='invalid_backend')
This may also depend on development trunk versions of other FEniCS programs. """ from pyop2 import op2, utils from pyop2.ffc_interface import compile_form from ufl import * import ffc import numpy as np parser = utils.parser(group=True, description=__doc__) parser.add_argument('-s', '--save-output', action='store_true', help='Save the output of the run (used for testing)') opt = vars(parser.parse_args()) op2.init(**opt) # Set up finite element identity problem E = FiniteElement("Lagrange", "triangle", 1) v = TestFunction(E) u = TrialFunction(E) f = Coefficient(E) a = v*u*dx L = v*f*dx # Generate code for mass and rhs assembly. mass, = compile_form(a, "mass")
def run(diffusivity, current_time, dt, endtime, **kwargs): op2.init(**kwargs) # Set up finite element problem T = FiniteElement("Lagrange", "triangle", 1) V = VectorElement("Lagrange", "triangle", 1) p = TrialFunction(T) q = TestFunction(T) t = Coefficient(T) u = Coefficient(V) diffusivity = 0.1 M = p * q * dx adv_rhs = (q * t + dt * dot(grad(q), u) * t) * dx d = -dt * diffusivity * dot(grad(q), grad(p)) * dx diff_matrix = M - 0.5 * d diff_rhs = action(M + 0.5 * d, t) # Generate code for mass and rhs assembly. mass = compile_form(M, "mass")[0] adv_rhs = compile_form(adv_rhs, "adv_rhs")[0] diff_matrix = compile_form(diff_matrix, "diff_matrix")[0] diff_rhs = compile_form(diff_rhs, "diff_rhs")[0] # Set up simulation data structures valuetype = np.float64 nodes, coords, elements, elem_node = read_triangle(kwargs['mesh']) num_nodes = nodes.size sparsity = op2.Sparsity((elem_node, elem_node), 1, "sparsity") mat = op2.Mat(sparsity, valuetype, "mat") tracer_vals = np.asarray([0.0] * num_nodes, dtype=valuetype) tracer = op2.Dat(nodes, 1, tracer_vals, valuetype, "tracer") b_vals = np.asarray([0.0] * num_nodes, dtype=valuetype) b = op2.Dat(nodes, 1, b_vals, valuetype, "b") velocity_vals = np.asarray([1.0, 0.0] * num_nodes, dtype=valuetype) velocity = op2.Dat(nodes, 2, velocity_vals, valuetype, "velocity") # Set initial condition i_cond_code = """ void i_cond(double *c, double *t) { double i_t = 0.01; // Initial time double A = 0.1; // Normalisation double D = 0.1; // Diffusivity double pi = 3.141459265358979; double x = c[0]-0.5; double y = c[1]-0.5; double r = sqrt(x*x+y*y); if (r<0.25) *t = A*(exp((-(r*r))/(4*D*i_t))/(4*pi*D*i_t)); else *t = 0.0; } """ i_cond = op2.Kernel(i_cond_code, "i_cond") op2.par_loop(i_cond, nodes, coords(op2.IdentityMap, op2.READ), tracer(op2.IdentityMap, op2.WRITE)) zero_dat_code = """ void zero_dat(double *dat) { *dat = 0.0; } """ zero_dat = op2.Kernel(zero_dat_code, "zero_dat") # Assemble and solve have_advection = True have_diffusion = True def timestep_iteration(): # Advection if have_advection: tic('advection') tic('assembly') mat.zero() op2.par_loop( mass, elements(3, 3), mat((elem_node[op2.i[0]], elem_node[op2.i[1]]), op2.INC), coords(elem_node, op2.READ)) op2.par_loop(zero_dat, nodes, b(op2.IdentityMap, op2.WRITE)) op2.par_loop(adv_rhs, elements(3), b(elem_node[op2.i[0]], op2.INC), coords(elem_node, op2.READ), tracer(elem_node, op2.READ), velocity(elem_node, op2.READ)) toc('assembly') tic('solve') op2.solve(mat, tracer, b) toc('solve') toc('advection') # Diffusion if have_diffusion: tic('diffusion') tic('assembly') mat.zero() op2.par_loop( diff_matrix, elements(3, 3), mat((elem_node[op2.i[0]], elem_node[op2.i[1]]), op2.INC), coords(elem_node, op2.READ)) op2.par_loop(zero_dat, nodes, b(op2.IdentityMap, op2.WRITE)) op2.par_loop(diff_rhs, elements(3), b(elem_node[op2.i[0]], op2.INC), coords(elem_node, op2.READ), tracer(elem_node, op2.READ)) toc('assembly') tic('solve') op2.solve(mat, tracer, b) toc('solve') toc('diffusion') # Perform 1 iteration to warm up plan cache then reset initial condition timestep_iteration() op2.par_loop(i_cond, nodes, coords(op2.IdentityMap, op2.READ), tracer(op2.IdentityMap, op2.WRITE)) reset() # Timed iteration t1 = clock() while current_time < endtime: timestep_iteration() current_time += dt runtime = clock() - t1 print "/fluidity :: %f" % runtime summary('profile_pyop2_%s_%s.csv' % (opt['mesh'].split('/')[-1], opt['backend']))
from math import sqrt parser = utils.parser(group=True, description=__doc__) parser.add_argument('-s', '--single', action='store_true', help='single precision floating point mode') parser.add_argument('-n', '--niter', action='store', default=2, type=int, help='set the number of iteration') opt = vars(parser.parse_args()) op2.init(**opt) fp_type = np.float32 if opt['single'] else np.float64 NN = 6 NITER = opt['niter'] nnode = (NN - 1)**2 nedge = nnode + 4 * (NN - 1) * (NN - 2) pp = np.zeros((2 * nedge, ), dtype=np.int) A = np.zeros((nedge, ), dtype=fp_type) r = np.zeros((nnode, ), dtype=fp_type) u = np.zeros((nnode, ), dtype=fp_type) du = np.zeros((nnode, ), dtype=fp_type)
def run(diffusivity, current_time, dt, endtime, **kwargs): op2.init(**kwargs) # Set up finite element problem T = FiniteElement("Lagrange", "triangle", 1) V = VectorElement("Lagrange", "triangle", 1) p = TrialFunction(T) q = TestFunction(T) t = Coefficient(T) u = Coefficient(V) diffusivity = 0.1 M = p * q * dx adv_rhs = (q * t + dt * dot(grad(q), u) * t) * dx d = -dt * diffusivity * dot(grad(q), grad(p)) * dx diff_matrix = M - 0.5 * d diff_rhs = action(M + 0.5 * d, t) # Generate code for mass and rhs assembly. mass = compile_form(M, "mass")[0] adv_rhs = compile_form(adv_rhs, "adv_rhs")[0] diff_matrix = compile_form(diff_matrix, "diff_matrix")[0] diff_rhs = compile_form(diff_rhs, "diff_rhs")[0] # Set up simulation data structures valuetype = np.float64 nodes, coords, elements, elem_node = read_triangle(kwargs["mesh"]) num_nodes = nodes.size sparsity = op2.Sparsity((elem_node, elem_node), 1, "sparsity") mat = op2.Mat(sparsity, valuetype, "mat") tracer_vals = np.asarray([0.0] * num_nodes, dtype=valuetype) tracer = op2.Dat(nodes, 1, tracer_vals, valuetype, "tracer") b_vals = np.asarray([0.0] * num_nodes, dtype=valuetype) b = op2.Dat(nodes, 1, b_vals, valuetype, "b") velocity_vals = np.asarray([1.0, 0.0] * num_nodes, dtype=valuetype) velocity = op2.Dat(nodes, 2, velocity_vals, valuetype, "velocity") # Set initial condition i_cond_code = """ void i_cond(double *c, double *t) { double i_t = 0.01; // Initial time double A = 0.1; // Normalisation double D = 0.1; // Diffusivity double pi = 3.141459265358979; double x = c[0]-0.5; double y = c[1]-0.5; double r = sqrt(x*x+y*y); if (r<0.25) *t = A*(exp((-(r*r))/(4*D*i_t))/(4*pi*D*i_t)); else *t = 0.0; } """ i_cond = op2.Kernel(i_cond_code, "i_cond") op2.par_loop(i_cond, nodes, coords(op2.IdentityMap, op2.READ), tracer(op2.IdentityMap, op2.WRITE)) zero_dat_code = """ void zero_dat(double *dat) { *dat = 0.0; } """ zero_dat = op2.Kernel(zero_dat_code, "zero_dat") # Assemble and solve have_advection = True have_diffusion = True def timestep_iteration(): # Advection if have_advection: tic("advection") tic("assembly") mat.zero() op2.par_loop( mass, elements(3, 3), mat((elem_node[op2.i[0]], elem_node[op2.i[1]]), op2.INC), coords(elem_node, op2.READ), ) op2.par_loop(zero_dat, nodes, b(op2.IdentityMap, op2.WRITE)) op2.par_loop( adv_rhs, elements(3), b(elem_node[op2.i[0]], op2.INC), coords(elem_node, op2.READ), tracer(elem_node, op2.READ), velocity(elem_node, op2.READ), ) toc("assembly") tic("solve") op2.solve(mat, tracer, b) toc("solve") toc("advection") # Diffusion if have_diffusion: tic("diffusion") tic("assembly") mat.zero() op2.par_loop( diff_matrix, elements(3, 3), mat((elem_node[op2.i[0]], elem_node[op2.i[1]]), op2.INC), coords(elem_node, op2.READ), ) op2.par_loop(zero_dat, nodes, b(op2.IdentityMap, op2.WRITE)) op2.par_loop( diff_rhs, elements(3), b(elem_node[op2.i[0]], op2.INC), coords(elem_node, op2.READ), tracer(elem_node, op2.READ), ) toc("assembly") tic("solve") op2.solve(mat, tracer, b) toc("solve") toc("diffusion") # Perform 1 iteration to warm up plan cache then reset initial condition timestep_iteration() op2.par_loop(i_cond, nodes, coords(op2.IdentityMap, op2.READ), tracer(op2.IdentityMap, op2.WRITE)) reset() # Timed iteration t1 = clock() while current_time < endtime: timestep_iteration() current_time += dt runtime = clock() - t1 print "/fluidity :: %f" % runtime summary("profile_pyop2_%s_%s.csv" % (opt["mesh"].split("/")[-1], opt["backend"]))
def initializer(request): lazy = request.param op2.init(lazy_evaluation=(lazy == "lazy")) return lazy
"""PyOP2 sparsity building benchmark""" import numpy as np from time import clock from pyop2 import op2, utils def time_sparsity(n): nodes = op2.Set(n) cells = op2.Set(n - 1) m = op2.Map(cells, nodes, 2, np.concatenate((np.arange(n - 1), np.arange(1, n)))) t = clock() s = op2.Sparsity((m, m), 1) return clock() - t if __name__ == '__main__': import pylab parser = utils.parser(group=True, description=__doc__) op2.init(**vars(parser.parse_args())) n = [2**i for i in range(10, 18)] t = [time_sparsity(i) for i in n] pylab.plot(n, t) pylab.xlabel('Sparsity size') pylab.ylabel('Sparsity build time (s)') pylab.show()
_expr_count = 0 V, E = badata.quickLoad(badata.MANHATTAN) if _VERBOSE: print V.head() print E.head() POSES_PER_CONSTRAINT = 2 POSES_DIM = balib.dim_lookup[V.label.unique()[0]] CONSTRAINT_DIM = balib.dim_lookup[E.label.unique()[0]] OMEGA_DOF = balib.omega_dof(CONSTRAINT_DIM) NUM_POSES = len(V) NUM_CONSTRAINTS = len(E) op2.init(backend='sequential') def testKernel(data=None, op2set=None, op2map=None): """ for testing purposes, it just prints out the data Dat array (assuming) it has dimension 3 in its Map (op2map). The kernel iterates over the Set op2set, if no arguments are passed in, this creates dummy values and prints them out """ if not op2set: op2set = op2.Set(5, 'fromset') if not op2map: op2toset = op2.Set(4, 'toset') npmapping = np.array([0, 1, 1, 2, 2, 3, 3, 1, 3, 2], np.uint32) print '-' * 80 print 'mapping: ', npmapping, npmapping.dtype, npmapping.shape
def test_double_init(self, backend): "Calling init again with the same backend should update the configuration." op2.init(backend=backend, foo='bar') assert op2.backends.get_backend() == 'pyop2.' + backend assert cfg.foo == 'bar'
def test_change_backend_fails(self, backend): "Calling init again with a different backend should fail." with pytest.raises(RuntimeError): op2.init(backend='other')
"""PyOP2 sparsity building benchmark""" import numpy as np from time import clock from pyop2 import op2, utils def time_sparsity(n): nodes = op2.Set(n) cells = op2.Set(n-1) m = op2.Map(cells, nodes, 2, np.concatenate((np.arange(n-1), np.arange(1,n)))) t = clock() s = op2.Sparsity((m,m), 1) return clock() - t if __name__=='__main__': import pylab parser = utils.parser(group=True, description=__doc__) op2.init(**vars(parser.parse_args())) n = [2**i for i in range(10,18)] t = [time_sparsity(i) for i in n] pylab.plot(n,t) pylab.xlabel('Sparsity size') pylab.ylabel('Sparsity build time (s)') pylab.show()