def as_python(mesh, function_name="make_mesh"): """Return a snippet of Python code (as a string) that will recreate the mesh given as an input parameter. """ from pytools.py_codegen import PythonCodeGenerator, Indentation cg = PythonCodeGenerator() cg(""" # generated by meshmode.mesh.as_python import numpy as np from meshmode.mesh import ( Mesh, MeshElementGroup, FacialAdjacencyGroup, BTAG_ALL, BTAG_REALLY_ALL) """) cg("def %s():" % function_name) with Indentation(cg): cg("vertices = " + _numpy_array_as_python(mesh.vertices)) cg("") cg("groups = []") cg("") for group in mesh.groups: cg("import %s" % type(group).__module__) cg("groups.append(%s.%s(" % ( type(group).__module__, type(group).__name__)) cg(" order=%s," % group.order) cg(" vertex_indices=%s," % _numpy_array_as_python(group.vertex_indices)) cg(" nodes=%s," % _numpy_array_as_python(group.nodes)) cg(" unit_nodes=%s))" % _numpy_array_as_python(group.unit_nodes)) # {{{ facial adjacency groups def fagrp_params_str(fagrp): params = { "igroup": fagrp.igroup, "ineighbor_group": repr(fagrp.ineighbor_group), "elements": _numpy_array_as_python(fagrp.elements), "element_faces": _numpy_array_as_python(fagrp.element_faces), "neighbors": _numpy_array_as_python(fagrp.neighbors), "neighbor_faces": _numpy_array_as_python(fagrp.neighbor_faces), } return ",\n ".join("%s=%s" % (k, v) for k, v in six.iteritems(params)) if mesh._facial_adjacency_groups: cg("facial_adjacency_groups = []") for igrp, fagrp_map in enumerate(mesh.facial_adjacency_groups): cg("facial_adjacency_groups.append({%s})" % ",\n ".join( "%r: FacialAdjacencyGroup(%s)" % ( inb_grp, fagrp_params_str(fagrp)) for inb_grp, fagrp in six.iteritems(fagrp_map))) else: cg("facial_adjacency_groups = %r" % mesh._facial_adjacency_groups) # }}} # {{{ boundary tags def strify_boundary_tag(btag): if isinstance(btag, type): return btag.__name__ else: return repr(btag) btags_str = ", ".join( strify_boundary_tag(btag) for btag in mesh.boundary_tags) # }}} cg("return Mesh(vertices, groups, skip_tests=True,") cg(" vertex_id_dtype=np.%s," % mesh.vertex_id_dtype.name) cg(" element_id_dtype=np.%s," % mesh.element_id_dtype.name) if isinstance(mesh._nodal_adjacency, NodalAdjacency): el_con_str = "(%s, %s)" % ( _numpy_array_as_python( mesh._nodal_adjacency.neighbors_starts), _numpy_array_as_python( mesh._nodal_adjacency.neighbors), ) else: el_con_str = repr(mesh._nodal_adjacency) cg(" nodal_adjacency=%s," % el_con_str) cg(" facial_adjacency_groups=facial_adjacency_groups,") cg(" boundary_tags=[%s])" % btags_str) # FIXME: Handle facial adjacency, boundary tags return cg.get()
def as_python(mesh, function_name="make_mesh"): """Return a snippet of Python code (as a string) that will recreate the mesh given as an input parameter. """ from pytools.py_codegen import PythonCodeGenerator, Indentation cg = PythonCodeGenerator() cg(""" # generated by meshmode.mesh.as_python import numpy as np from meshmode.mesh import ( Mesh, MeshElementGroup, FacialAdjacencyGroup, BTAG_ALL, BTAG_REALLY_ALL) """) cg("def %s():" % function_name) with Indentation(cg): cg("vertices = " + _numpy_array_as_python(mesh.vertices)) cg("") cg("groups = []") cg("") for group in mesh.groups: cg("import %s" % type(group).__module__) cg("groups.append(%s.%s(" % ( type(group).__module__, type(group).__name__)) cg(" order=%s," % group.order) cg(" vertex_indices=%s," % _numpy_array_as_python(group.vertex_indices)) cg(" nodes=%s," % _numpy_array_as_python(group.nodes)) cg(" unit_nodes=%s))" % _numpy_array_as_python(group.unit_nodes)) # {{{ facial adjacency groups def fagrp_params_str(fagrp): params = { "igroup": fagrp.igroup, "ineighbor_group": repr(fagrp.ineighbor_group), "elements": _numpy_array_as_python(fagrp.elements), "element_faces": _numpy_array_as_python(fagrp.element_faces), "neighbors": _numpy_array_as_python(fagrp.neighbors), "neighbor_faces": _numpy_array_as_python(fagrp.neighbor_faces), } return ",\n ".join("%s=%s" % (k, v) for k, v in six.iteritems(params)) if mesh._facial_adjacency_groups: cg("facial_adjacency_groups = []") for igrp, fagrp_map in enumerate(mesh.facial_adjacency_groups): cg("facial_adjacency_groups.append({%s})" % ",\n ".join( "%r: FacialAdjacencyGroup(%s)" % ( inb_grp, fagrp_params_str(fagrp)) for inb_grp, fagrp in six.iteritems(fagrp_map))) else: cg("facial_adjacency_groups = %r" % mesh._facial_adjacency_groups) # }}} # {{{ boundary tags def strify_boundary_tag(btag): if isinstance(btag, type): return btag.__name__ else: return repr(btag) btags_str = ", ".join( strify_boundary_tag(btag) for btag in mesh.boundary_tags) # }}} cg("return Mesh(vertices, groups, skip_tests=True,") cg(" vertex_id_dtype=np.%s," % mesh.vertex_id_dtype.name) cg(" element_id_dtype=np.%s," % mesh.element_id_dtype.name) if isinstance(mesh._nodal_adjacency, NodalAdjacency): el_con_str = "(%s, %s)" % ( _numpy_array_as_python( mesh._nodal_adjacency.neighbors_starts), _numpy_array_as_python( mesh._nodal_adjacency.neighbors), ) else: el_con_str = repr(mesh._nodal_adjacency) cg(" nodal_adjacency=%s," % el_con_str) cg(" facial_adjacency_groups=facial_adjacency_groups,") cg(" boundary_tags=[%s])" % btags_str) # FIXME: Handle facial adjacency, boundary tags return cg.get()
def capture_kernel_call(kernel, filename, queue, g_size, l_size, *args, **kwargs): try: source = kernel._source except AttributeError: raise RuntimeError("cannot capture call, kernel source not available") if source is None: raise RuntimeError("cannot capture call, kernel source not available") cg = PythonCodeGenerator() cg("# generated by pyopencl.capture_call") cg("") cg("import numpy as np") cg("import pyopencl as cl") cg("from base64 import b64decode") cg("from zlib import decompress") cg("mf = cl.mem_flags") cg("") cg('CODE = r"""//CL//') for l in source.split("\n"): cg(l) cg('"""') # {{{ invocation arg_data = [] cg("") cg("") cg("def main():") with Indentation(cg): cg("ctx = cl.create_some_context()") cg("queue = cl.CommandQueue(ctx)") cg("") kernel_args = [] for i, arg in enumerate(args): if isinstance(arg, cl.Buffer): buf = bytearray(arg.size) cl.enqueue_copy(queue, buf, arg) arg_data.append(("arg%d_data" % i, buf)) cg("arg%d = cl.Buffer(ctx, " "mf.READ_WRITE | cl.mem_flags.COPY_HOST_PTR," % i) cg(" hostbuf=decompress(b64decode(arg%d_data)))" % i) kernel_args.append("arg%d" % i) elif isinstance(arg, (int, float)): kernel_args.append(repr(arg)) elif isinstance(arg, np.integer): kernel_args.append("np.%s(%s)" % (arg.dtype.type.__name__, repr(int(arg)))) elif isinstance(arg, np.floating): kernel_args.append("np.%s(%s)" % (arg.dtype.type.__name__, repr(float(arg)))) elif isinstance(arg, np.complexfloating): kernel_args.append("np.%s(%s)" % (arg.dtype.type.__name__, repr(complex(arg)))) else: try: arg_buf = buffer(arg) except: raise RuntimeError("cannot capture: " "unsupported arg nr %d (0-based)" % i) arg_data.append(("arg%d_data" % i, arg_buf)) kernel_args.append("decompress(b64decode(arg%d_data))" % i) cg("") g_times_l = kwargs.get("g_times_l", False) if g_times_l: dim = max(len(g_size), len(l_size)) l_size = l_size + (1,) * (dim - len(l_size)) g_size = g_size + (1,) * (dim - len(g_size)) g_size = tuple(gs * ls for gs, ls in zip(g_size, l_size)) global_offset = kwargs.get("global_offset", None) if global_offset is not None: kernel_args.append("global_offset=%s" % repr(global_offset)) cg("prg = cl.Program(ctx, CODE).build()") cg("knl = prg.%s" % kernel.function_name) if hasattr(kernel, "_arg_type_chars"): cg("knl._arg_type_chars = %s" % repr(kernel._arg_type_chars)) cg("knl(queue, %s, %s," % (repr(g_size), repr(l_size))) cg(" %s)" % ", ".join(kernel_args)) cg("") cg("queue.finish()") # }}} # {{{ data from zlib import compress from base64 import b64encode cg("") line_len = 70 for name, val in arg_data: cg("%s = (" % name) with Indentation(cg): val = str(b64encode(compress(buffer(val)))) i = 0 while i < len(val): cg(repr(val[i : i + line_len])) i += line_len cg(")") # }}} # {{{ file trailer cg("") cg('if __name__ == "__main__":') with Indentation(cg): cg("main()") cg("") cg("# vim: filetype=pyopencl") # }}} with open(filename, "w") as outf: outf.write(cg.get())
def capture_kernel_call(kernel, filename, queue, g_size, l_size, *args, **kwargs): try: source = kernel._source except AttributeError: raise RuntimeError("cannot capture call, kernel source not available") if source is None: raise RuntimeError("cannot capture call, kernel source not available") cg = PythonCodeGenerator() cg("# generated by pyopencl.capture_call") cg("") cg("import numpy as np") cg("import pyopencl as cl") cg("from base64 import b64decode") cg("from zlib import decompress") cg("mf = cl.mem_flags") cg("") cg('CODE = r"""//CL//') for line in source.split("\n"): cg(line) cg('"""') # {{{ invocation arg_data = [] cg("") cg("") cg("def main():") with Indentation(cg): cg("ctx = cl.create_some_context()") cg("queue = cl.CommandQueue(ctx)") cg("") kernel_args = [] for i, arg in enumerate(args): if isinstance(arg, cl.Buffer): buf = bytearray(arg.size) cl.enqueue_copy(queue, buf, arg) arg_data.append(("arg%d_data" % i, buf)) cg("arg%d = cl.Buffer(ctx, " "mf.READ_WRITE | cl.mem_flags.COPY_HOST_PTR," % i) cg(" hostbuf=decompress(b64decode(arg%d_data)))" % i) kernel_args.append("arg%d" % i) elif isinstance(arg, (int, float)): kernel_args.append(repr(arg)) elif isinstance(arg, np.integer): kernel_args.append("np.%s(%s)" % (arg.dtype.type.__name__, repr(int(arg)))) elif isinstance(arg, np.floating): kernel_args.append("np.%s(%s)" % (arg.dtype.type.__name__, repr(float(arg)))) elif isinstance(arg, np.complexfloating): kernel_args.append( "np.%s(%s)" % (arg.dtype.type.__name__, repr(complex(arg)))) else: try: arg_buf = memoryview(arg) except Exception: raise RuntimeError("cannot capture: " "unsupported arg nr %d (0-based)" % i) arg_data.append(("arg%d_data" % i, arg_buf)) kernel_args.append("decompress(b64decode(arg%d_data))" % i) cg("") g_times_l = kwargs.get("g_times_l", False) if g_times_l: dim = max(len(g_size), len(l_size)) l_size = l_size + (1, ) * (dim - len(l_size)) g_size = g_size + (1, ) * (dim - len(g_size)) g_size = tuple(gs * ls for gs, ls in zip(g_size, l_size)) global_offset = kwargs.get("global_offset", None) if global_offset is not None: kernel_args.append("global_offset=%s" % repr(global_offset)) cg("prg = cl.Program(ctx, CODE).build()") cg("knl = prg.%s" % kernel.function_name) if hasattr(kernel, "_scalar_arg_dtypes"): def strify_dtype(d): if d is None: return "None" d = np.dtype(d) s = repr(d) if s.startswith("dtype"): s = "np." + s return s cg("knl.set_scalar_arg_dtypes((%s,))" % ", ".join(strify_dtype(dt) for dt in kernel._scalar_arg_dtypes)) cg("knl(queue, %s, %s," % (repr(g_size), repr(l_size))) cg(" %s)" % ", ".join(kernel_args)) cg("") cg("queue.finish()") # }}} # {{{ data from zlib import compress from base64 import b64encode cg("") line_len = 70 for name, val in arg_data: cg("%s = (" % name) with Indentation(cg): val = str(b64encode(compress(memoryview(val)))) i = 0 while i < len(val): cg(repr(val[i:i + line_len])) i += line_len cg(")") # }}} # {{{ file trailer cg("") cg("if __name__ == \"__main__\":") with Indentation(cg): cg("main()") cg("") cg("# vim: filetype=pyopencl") # }}} with open(filename, "w") as outf: outf.write(cg.get())