def test_physically_mapped_facet(): mesh = Mesh(VectorElement("P", triangle, 1)) # set up variational problem U = FiniteElement("Morley", mesh.ufl_cell(), 2) V = FiniteElement("P", mesh.ufl_cell(), 1) R = FiniteElement("P", mesh.ufl_cell(), 1) Vv = VectorElement(BrokenElement(V)) Qhat = VectorElement(BrokenElement(V[facet])) Vhat = VectorElement(V[facet]) Z = FunctionSpace(mesh, MixedElement(U, Vv, Qhat, Vhat, R)) z = Coefficient(Z) u, d, qhat, dhat, lam = split(z) s = FacetNormal(mesh) trans = as_matrix([[1, 0], [0, 1]]) mat = trans*grad(grad(u))*trans + outer(d, d) * u J = (u**2*dx + u**3*dx + u**4*dx + inner(mat, mat)*dx + inner(grad(d), grad(d))*dx + dot(s, d)**2*ds) L_match = inner(qhat, dhat - d) L = J + inner(lam, inner(d, d)-1)*dx + (L_match('+') + L_match('-'))*dS + L_match*ds compile_form(L)
def test_cell_error(cell, degree): """Test that tabulating the trace element deliberatly on the cell triggers `gem.Failure` to raise the TraceError exception. """ trace_element = FiniteElement("HDiv Trace", cell, degree) lambdar = TrialFunction(trace_element) gammar = TestFunction(trace_element) with pytest.raises(TraceError): compile_form(lambdar * gammar * dx)
def test_gradient_error(cell, degree): """Test that tabulating gradient evaluations of the trace element triggers `gem.Failure` to raise the TraceError exception. """ trace_element = FiniteElement("HDiv Trace", cell, degree) lambdar = TrialFunction(trace_element) gammar = TestFunction(trace_element) with pytest.raises(TraceError): compile_form(inner(grad(lambdar('+')), grad(gammar('+'))) * dS)
def test_idempotency(form): k1 = compile_form(form)[0] k2 = compile_form(form)[0] assert k1.ast.gencode() == k2.ast.gencode() # Test loopy backend import loopy k1 = compile_form(form, coffee=False)[0] k2 = compile_form(form, coffee=False)[0] assert loopy.generate_code_v2( k1.ast).device_code() == loopy.generate_code_v2(k2.ast).device_code()
def test_estimated_degree(): cell = ufl.tetrahedron mesh = ufl.Mesh(ufl.VectorElement('P', cell, 1)) V = ufl.FunctionSpace(mesh, ufl.FiniteElement('P', cell, 1)) f = ufl.Coefficient(V) u = ufl.TrialFunction(V) v = ufl.TestFunction(V) a = u * v * ufl.tanh(ufl.sqrt(ufl.sinh(f) / ufl.sin(f**f))) * ufl.dx handler = MockHandler() logger.addHandler(handler) with pytest.raises(RuntimeError): compile_form(a) logger.removeHandler(handler)
def compile_form(form): idx_kernels_list = [] # A map from all form coefficients to their number. coefficient_numbers = dict( (c, n) for (n, c) in enumerate(form.coefficients())) for idx, f in split_form(form): arg = f.arguments() coeff = f.coefficients() numbering = f.coefficient_numbering() # Map local coefficient numbers (as seen inside the # compiler) to the global coefficient numbers number_map = dict((n, coefficient_numbers[c]) for (n, c) in enumerate(f.coefficients())) tsfc_kernels = tsfc.compile_form(f) kernels = [] for kernel in tsfc_kernels: tkernel = ThemisKernel(kernel) tkernel.formdim = len(f.arguments()) #map kernel coefficient numbers to global coefficient numbers numbers = tuple(number_map[c] for c in kernel.coefficient_numbers) tkernel.coefficient_map = numbers tkernel.coefficients = form.coefficients() tkernel.name = kernel.ast.operands()[0][1] tkernel.mesh = form.ufl_domain() kernels.append(tkernel) idx_kernels_list.append((idx, kernels)) return idx_kernels_list
def count_flops(n): mesh = Mesh(VectorElement('CG', interval, 1)) tfs = FunctionSpace(mesh, TensorElement('DG', interval, 1, shape=(n, n))) vfs = FunctionSpace(mesh, VectorElement('DG', interval, 1, dim=n)) ensemble_f = Coefficient(vfs) ensemble2_f = Coefficient(vfs) phi = TestFunction(tfs) i, j = indices(2) nc = 42 # magic number L = ((IndexSum( IndexSum( Product(nc * phi[i, j], Product(ensemble_f[i], ensemble_f[i])), MultiIndex((i, ))), MultiIndex((j, ))) * dx) + (IndexSum( IndexSum( Product(nc * phi[i, j], Product( ensemble2_f[j], ensemble2_f[j])), MultiIndex( (i, ))), MultiIndex((j, ))) * dx) - (IndexSum( IndexSum( 2 * nc * Product(phi[i, j], Product(ensemble_f[i], ensemble2_f[j])), MultiIndex((i, ))), MultiIndex((j, ))) * dx)) kernel, = compile_form(L, parameters=dict(mode='spectral')) return EstimateFlops().visit(kernel.ast)
def compile_form(form): idx_kernels_list = [] # A map from all form coefficients to their number. coefficient_numbers = dict( (c, n) for (n, c) in enumerate(form.coefficients())) for idx, f in split_form(form): # Map local coefficient numbers (as seen inside the # compiler) to the global coefficient numbers number_map = dict((n, coefficient_numbers[c]) for (n, c) in enumerate(f.coefficients())) tsfc_kernels = tsfc.compile_form( f, interface=kernel_interface.KernelBuilder) kernels = [] for kernel in tsfc_kernels: tkernel = ThemisKernel(kernel) tkernel.formdim = len(f.arguments()) # map kernel coefficient numbers to global coefficient numbers numbers = tuple(number_map[c] for c in kernel.coefficient_numbers) tkernel.coefficient_map = numbers tkernel.coefficients = form.coefficients() tkernel.name = kernel.ast.name tkernel.mesh = form.ufl_domain() tkernel.finatquad = kernel.quadrature_rule tkernel.tabulations = [] for tabname, shape in kernel.tabulations: splittab = tabname.split('_') tabobj = {} tabobj['name'] = tabname # this matches the string generated in runtime_tabulated.py in FInAT # ie variant_order_derivorder_shiftaxis_{d,c}_restrict tabobj['variant'] = splittab[1] tabobj['order'] = int(splittab[2]) tabobj['derivorder'] = int(splittab[3]) tabobj['shiftaxis'] = int(splittab[4]) if splittab[5] == 'd': tabobj['cont'] = 'L2' if splittab[5] == 'c': tabobj['cont'] = 'H1' tabobj['restrict'] = splittab[6] tabobj['shape'] = shape tkernel.tabulations.append(tabobj) kernels.append(tkernel) idx_kernels_list.append((idx, kernels)) return idx_kernels_list
def tsfc_compile_wrapper(form, parameters=None): """Compile form with TSFC and return source code""" parameters_ = {'mode': 'spectral'} parameters_.update(parameters or {}) kernel, = tsfc.compile_form(form, parameters=parameters_) k = ASTKernel(kernel.ast) k.plan_cpu(dict(optlevel='Ov')) code = kernel.ast.gencode() code = code.replace('static inline', '') code = "#include <math.h>\n\n" + code return code
def count_flops(n): mesh = Mesh(VectorElement('CG', interval, 1)) tfs = FunctionSpace(mesh, TensorElement('DG', interval, 1, shape=(n, n))) vfs = FunctionSpace(mesh, VectorElement('DG', interval, 1, dim=n)) ensemble_f = Coefficient(vfs) ensemble2_f = Coefficient(vfs) phi = TestFunction(tfs) i, j = indices(2) nc = 42 # magic number L = ((IndexSum(IndexSum(Product(nc * phi[i, j], Product(ensemble_f[i], ensemble_f[i])), MultiIndex((i,))), MultiIndex((j,))) * dx) + (IndexSum(IndexSum(Product(nc * phi[i, j], Product(ensemble2_f[j], ensemble2_f[j])), MultiIndex((i,))), MultiIndex((j,))) * dx) - (IndexSum(IndexSum(2 * nc * Product(phi[i, j], Product(ensemble_f[i], ensemble2_f[j])), MultiIndex((i,))), MultiIndex((j,))) * dx)) kernel, = compile_form(L, parameters=dict(mode='spectral')) return EstimateFlops().visit(kernel.ast)
def tsfc_compile_form(form, parameters=None): import tsfc tic = time() # FFC generates C strings, TSFC generates a COFFEE AST. # Convert COFFEE AST to C string for fairness. kernel, = tsfc.compile_form(form, parameters=parameters) code = kernel.ast.gencode() T1 = time() - tic print('#include <math.h>\n', '#include <string.h>\n', code.replace('static inline', '', 1), file=open("Form.c", 'w')) tic = time() subprocess.check_call(["cc", "-pipe", "-c", "-O2", "-std=c99", "Form.c"]) T2 = time() - tic inst = int(subprocess.check_output("objdump -d Form.o | wc -l", shell=True)) return T1 + T2, inst
def test_delta_elimination(mode): # Code sample courtesy of Marco Morandini: # https://github.com/firedrakeproject/tsfc/issues/182 scheme = "default" degree = 3 element_lambda = FiniteElement("Quadrature", tetrahedron, degree, quad_scheme=scheme) element_eps_p = VectorElement("Quadrature", tetrahedron, degree, dim=6, quad_scheme=scheme) element_chi_lambda = MixedElement(element_eps_p, element_lambda) chi_lambda = Coefficient(element_chi_lambda) delta_chi_lambda = TestFunction(element_chi_lambda) L = inner(delta_chi_lambda, chi_lambda) * dx(degree=degree, scheme=scheme) kernel, = compile_form(L, parameters={'mode': mode})
u = f.Function(fs) else: raise ValueError("Unknown operation: %s" % operation) if form_string == "u * v * dx": return u * v * dx elif form_string == "inner(grad(u), grad(v)) * dx": return inner(grad(u), grad(v)) * dx data = {} for dimension in 2, 3: data[dimension] = {} for operation in ("action",): # ("matrix", "action"): data[dimension][operation] = {} for form_string in ("u * v * dx", "inner(grad(u), grad(v)) * dx"): print "%s %s in %d dimensions" % (form_string, operation, dimension) flops = {} for d in range(1, 10): form = create_form(form_string, "Q", d, dimension, operation) ast = tsfc.compile_form(form)[0].ast flops[d] = coffee.visitors.EstimateFlops().visit(ast) print d, flops[d] if d > 1: print np.log(float(flops[d])/flops[d-1])/np.log(float(d)/float(d-1)) data[dimension][operation][form_string] = flops json.dump(data, file("data_count.json", "w"))
def test_idempotency(form): k1 = compile_form(form)[0] k2 = compile_form(form)[0] assert k1.ast.gencode() == k2.ast.gencode()
def count_flops(form): kernel, = compile_form(form, parameters=dict(mode='spectral')) return EstimateFlops().visit(kernel.ast)
print(y.vector()[:]) exit(0) cells = mesh.comm.allreduce(mesh.cell_set.size) dofs = mesh.comm.allreduce(V.dof_count) rank = mesh.comm.Get_rank() if rank == 0: if mesh.layers: cells = cells * (mesh.layers - 1) print("CELLS= {0}".format(cells)) print("DOFS= {0}".format(dofs)) from loopy.program import make_program knl = compile_form(y_form, coffee=False)[0].ast warnings = list(knl.silenced_warnings) warnings.extend(["insn_count_subgroups_upper_bound", "no_lid_found"]) knl = knl.copy(silenced_warnings=warnings) knl.options.ignore_boostable_into = True program = make_program(knl) op_map = lp.get_op_map(program, subgroup_size=1) mem_map = lp.get_mem_access_map(program, subgroup_size=1) for op in ['add', 'sub', 'mul', 'div']: print("{0}S= {1}".format( op.upper(), op_map.filter_by(name=[op], dtype=[np.float64]).eval_and_sum({}))) print("MEMS= {0}".format( mem_map.filter_by(mtype=['global'],