def test_repeated_build(): #_t = None def tic(): global _t _t = -time() def toc(msg=""): t = time() + _t print("t = %f (%s)" % (t, msg)) return t c_code = """ double sum(double a, double b) { return a+b; } """ # Time a few builds tic() module = build_module(code=c_code) t1 = toc("first build") tic() module = build_module(code=c_code) t2 = toc("second build") tic() module = build_module(code=c_code) t3 = toc("third build") assert t1 > t2 assert t1 > t3
def test_build_module(): build_module(code=c_code, modulename='test3_ext', cppargs=['-pg', '-O3', '-g'], lddargs=['-pg']) from test3_ext import sum a = 3.7 b = 4.8 c = sum(a, b) assert c == 8.5
def test_buil_module(): test5_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs=['-pg'], lddargs=['-pg'], include_dirs=[numpy.get_include()], init_code='import_array();', modulename='test5_ext', arrays = [['n1', 'array1'], ['n2', 'array2'], ['n3', 'array3']]) from test5_ext import add add = test5_ext.add a = numpy.arange(10000000); a = numpy.sin(a) b = numpy.arange(10000000); b = numpy.cos(b) c = numpy.arange(10000000); c = numpy.cos(c) d = numpy.arange(10000000); d = numpy.cos(d) t1 = time.time() add(a, b, c) t2 = time.time() print('With instant:', t2-t1, 'seconds') t1 = time.time() numpy.add(a, b, d) t2 = time.time() print('With numpy: ', t2-t1, 'seconds') difference = abs(d - c) sum = reduce( lambda a, b: a+b, difference) assert abs(sum) < 1.0e-12
def build_ufc_module(h_files, source_directory="", system_headers=None, \ **kwargs): """Build a python extension module from ufc compliant source code. The compiled module will be imported and returned by the function. @param h_files: The name(s) of the header files that should be compiled and included in the python extension module. @param source_directory: The directory where the source files reside. @param system_headers: Extra headers that will be #included in the generated wrapper file. Any additional keyword arguments are passed on to instant.build_module. """ # Check h_files argument if isinstance(h_files, str): h_files = [h_files] assert isinstance(h_files, list) , "Provide a 'list' or a 'str' as 'h_files'." assert all(isinstance(f, str) for f in h_files), \ "Elements of 'h_files' must be 'str'." h_files2 = [os.path.join(source_directory, fn) for fn in h_files] for f in h_files2: if not os.path.isfile(f): raise IOError("The file '%s' does not exist." % f) # Check system_headers argument system_headers = system_headers or [] assert isinstance(system_headers, list), "Provide a 'list' as 'system_headers'" assert all(isinstance(header, str) for header in system_headers), \ "Elements of 'system_headers' must be 'str'." system_headers.append("memory") # Get the swig interface file declarations declarations = extract_declarations(h_files2) declarations += """ // SWIG version %inline %{ int get_swigversion() { return SWIGVERSION; } %} %pythoncode %{ tmp = hex(get_swigversion()) swigversion = "%d.%d.%d"%(tuple(map(int, [tmp[-5], tmp[-3], tmp[-2:]]))) del tmp, get_swigversion %} """ # Call instant and return module return instant.build_module(wrap_headers = h_files, source_directory = source_directory, additional_declarations = declarations, system_headers = system_headers, cmake_packages = ["UFC"], **kwargs)
def test_build_module(): # Guess arrayobject is either in sys.prefix or /usr/local test6_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs=['-g'], include_dirs=[N.get_include()], init_code='import_array();', modulename='test6_ext', arrays = [['x1', 'y1', 'array1'], ['x2', 'y2', 'array2'], ['x3', 'y3', 'array3']]) from test6_ext import add a = N.arange(4000000); a = N.sin(a); a.shape=(2000, 2000) b = N.arange(4000000); b = N.cos(b); b.shape=(2000, 2000) c = N.arange(4000000); c = N.cos(c); c.shape=(2000, 2000) d = N.arange(4000000); d = N.cos(d); d.shape=(2000, 2000) t1 = time.time() add(a, b, c) t2 = time.time() t3 = time.time() N.add(a, b, d) t4 = time.time() e = abs(d-c) e.shape=(4000000,) max_difference = max(e) assert abs(max_difference) < 1.0e-12
def compile(self): """ Compile the code. """ args = "" cast_code = "" for name in sorted(self.__args.keys()): arg = self.__args[name] if len(args) > 0: args += ", " if arg == int: args += "int %s" % name elif arg == float: args += "double %s" % name elif arg == int_arr: args += "int* %s" % name elif arg == long_arr: args += "long* %s" % name elif arg == double_arr: args += "double* %s" % name else: name_mangle = name while name_mangle in self.__args.keys(): name_mangle = "%s_" % name_mangle args += "void* %s" % name_mangle cast_code += " shared_ptr<%s> %s = (*((shared_ptr<%s>*)%s));\n" % \ (self.__boost_classes[arg], name, self.__boost_classes[arg], name_mangle) code = \ """ %s // Keep SWIG happy namespace dolfin { } using namespace dolfin; extern "C" { int code(%s) { %s %s return 0; } }""" % (self.__includes, args, cast_code, self.__code) mod = instant.build_module(code = code, cppargs = dolfin.parameters["form_compiler"]["cpp_optimize_flags"], lddargs = "-ldolfin", include_dirs = self.__include_dirs, cmake_packages = ["DOLFIN"]) path = os.path.dirname(mod.__file__) name = os.path.split(path)[-1] self.__lib = ctypes.cdll.LoadLibrary(os.path.join(path, "_%s.so" % name)) self.__lib.code.restype = int return
def compile_functional(kernel,tspace,sspace,mesh): #NEEDS FIXING FOR CONSTANTS if not kernel.zero: #### THIS IS UGLY HACKING TO FIX INABILITY TO GET KERNELS TO WORK WITH CONST * CONST * RESTRICT STUFF #### ### REMOVE ONCE I FIGURE OUT WHAT IS GOING ON ######## ncoeff = len(kernel.coefficient_numbers) operands = kernel.ast.operands()[0] func_args = operands[2] elem = mesh.coordinates.function_space().themis_element() #first argument is the local tensor and second is always coords... func_args[1].qual = [] func_args[1].pointers = [] func_args[1].sym.rank = elem.get_local_size() k = 0 for i in range(ncoeff): field = kernel.coefficients[kernel.coefficient_map[i]] if isinstance(field,Function): for si in range(field.function_space().nspaces): elem = field.function_space().get_space(si).themis_element() arg = func_args[2+k] arg.qual = [] arg.pointers = [] arg.sym.rank = elem.get_local_size() k = k + 1 if isinstance(field,Constant): arg = func_args[2+k] arg.qual = [] arg.pointers = [] if len(field.dat.shape) >= 1: arg.sym.rank = np.prod(field.dat.shape) if len(field.dat.shape) == 0: arg.sym.rank = (1,) k = k + 1 ############################### #THIS NEEDS SOME SORT OF CACHING CHECK! assembly_routine = generate_assembly_routine(mesh,tspace,sspace,kernel) assembly_routine = assembly_routine.encode('ascii','ignore') kernel.assemble_function= instant.build_module( code=assembly_routine, include_dirs=include_dirs, library_dirs=library_dirs, libraries=libraries, init_code = ' import_array();', cppargs=['-O3',], swig_include_dirs=swig_include_dirs).assemble if not kernel.zero: kernel.assemblycompiled = True
def test_sum(): sig = "((instant unittest test16.py))" # Trying to import module module = import_module(sig, cache_dir="test_cache") if module is None: print("Defining code") c_code = """ class Sum { public: virtual double sum(double a, double b){ return a+b; } }; double use_Sum(Sum& sum, double a, double b) { return sum.sum(a,b); } """ print("Compiling code") module = build_module(code=c_code, signature=sig, cache_dir="test_cache") # Testing module Sum = module.Sum use_Sum = module.use_Sum sum = Sum() a = 3.7 b = 4.8 c = use_Sum(sum, a, b) print("The sum of %g and %g is %g"% (a, b, c)) class Sub(Sum): def __init__(self): Sum.__init__(self) def sum(self, a, b): print("sub") return a-b; sub = Sub() a = 3.7 b = 4.8 c = use_Sum(sub, a, b) print("The sub of %g and %g is %g"% (a, b, c))
def EvaluateCoefficient(coefficient, kernel): with PETSc.Log.Stage(coefficient.name() + '_assemble'): with PETSc.Log.Event('compile'): if not kernel.assemblycompiled: mesh = coefficient.mesh #THIS NEEDS SOME SORT OF CACHING CHECK! assembly_routine = generate_assembly_routine( mesh, None, None, kernel) assembly_routine = assembly_routine.encode('ascii', 'ignore') kernel.assemble_function = instant.build_module( code=assembly_routine, include_dirs=include_dirs, library_dirs=library_dirs, libraries=libraries, init_code=' import_array();', cppargs=[ '-O3', ], swig_include_dirs=swig_include_dirs).evaluate kernel.assemblycompiled = True #scatter fields into local vecs with PETSc.Log.Event('extract'): fieldargs_list = extract_fields(kernel) #evaluate with PETSc.Log.Event('evaluate'): for bi in range(coefficient.mesh.npatches): if kernel.integral_type == 'cell': da = coefficient.mesh.get_cell_da(bi) #if kernel.integral_type == 'facet' and functional.facet_direc == 'x': #da = coefficient.mesh.edgex_das[bi] #if kernel.integral_type == 'facet' and functional.facet_direc == 'y': #da = coefficient.mesh.edgey_das[bi] #if kernel.integral_type == 'facet' and functional.facet_direc == 'z': #da = coefficient.mesh.edgez_das[bi] #BROKEN FOR MULTIPATCH- FIELD ARGS LIST NEEDS A BI INDEX kernel.assemble_function( da, *([coefficient.dms[bi], coefficient.vecs[bi]] + fieldargs_list))
def test_build_module(): test4_ext = build_module(code=s, system_headers=["numpy/arrayobject.h"], include_dirs=[numpy.get_include()], init_code='import_array();', modulename="test4_ext") import time t1 = time.time() d = test4_ext.add(a, b) t2 = time.time() print('With instant:', t2 - t1, 'seconds') t1 = time.time() c = a + b t2 = time.time() print('With numpy: ', t2 - t1, 'seconds') difference = abs(c - d) sum = reduce( lambda a, b: a + b, difference) assert sum < 1.0e-12
def test_build_module(): test8_ext = build_module(code=c_code, modulename='test8_ext') from test8_ext import Sum, use_Sum sum = Sum() a = 3.7 b = 4.8 c = use_Sum(sum, a, b) assert c == 8.5 class Sub(Sum): def __init__(self): Sum.__init__(self) def sum(self, a, b): print("sub") return a - b sub = Sub() a = 3.7 b = 4.8 c = use_Sum(sub, a, b) assert c == 8.5
def test_module(): # Guess arrayobject is either in sys.prefix or /usr/local test7_ext = build_module(code=c_code, system_headers=["numpy/arrayobject.h"], cppargs='-g', include_dirs=[N.get_include()], init_code='import_array();', modulename='test7_ext', arrays=[['n1', 'array1'], ['n2', 'array2']]) seed = 10000000.0 a = N.arange(seed) t1 = time.time() b = N.sin(a) + N.cos(a) + N.tan(a) t2 = time.time() print("With NumPy: ", t2 - t1, "seconds") from test7_ext import func c = N.arange(seed) t1 = time.time() func(a, c) t2 = time.time() print("With instant: ", t2 - t1, "seconds") t1 = time.time() d = N.sin(a) d += N.cos(a) d += N.tan(a) t2 = time.time() print("With NumPy inplace aritmetic: ", t2 - t1, "seconds") difference = abs(b - c) sum = reduce(lambda a, b: a + b, difference) assert abs(sum) < 1.0e-12
def test_build(): #_t = None def tic(): global _t _t = -time.time() def toc(msg=""): t = time.time() + _t print("t = %f (%s)" % (t, msg)) return t c_code = """ double sum(double a, double b) { return a+b; } """ class Sig: def __init__(self, sig): self.sig = sig def signature(self): time.sleep(1.0) return self.sig def __hash__(self): time.sleep(0.5) return hash(self.sig) def __cmp__(self, other): if isinstance(other, Sig): return cmp(self.sig, other.sig) return -1 modulename = "test19_ext" cache_dir = "test19_cache" shutil.rmtree(cache_dir, ignore_errors=True) shutil.rmtree(modulename, ignore_errors=True) # Build and rebuild with explicit modulename tic() module = build_module(code=c_code, modulename=modulename, cache_dir=cache_dir) assert module is not None t1 = toc("(1) With modulename") tic() module = build_module(code=c_code, modulename=modulename, cache_dir=cache_dir) assert module is not None t2 = toc("(2) With modulename") assert t1 > t2 # Try importing module in a separate python process python_interp = sys.executable cmd = python_interp + ' -c "import %s"' % modulename print(cmd) stat = os.system(cmd) assert stat == 0 # a # Build and rebuild with a valid filename as signature sig = "test19_signature_module" tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t1 = toc("(1) With signature") tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t2 = toc("(2) With signature") assert t1 > t2 tic() module = import_module(sig, cache_dir) assert module is not None t3 = toc("(3) import_module") assert t1 > t3 # Try importing module in a separate python process python_interp = sys.executable cmd = python_interp + ' -c "import instant; assert instant.import_module(\'%s\', \'%s\') is not None"' % ( sig, cache_dir) print(cmd) stat = os.system(cmd) assert stat == 0 # b # Build and rebuild with generic signature string sig = "((test19_signature_module))" tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t1 = toc("(1) With signature") tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t2 = toc("(2) With signature") assert t1 > t2 tic() module = import_module(sig, cache_dir) assert module is not None t3 = toc("(3) import_module") assert t1 > t3 # Try importing module in a separate python process python_interp = sys.executable cmd = python_interp + ' -c "import instant; assert instant.import_module(\'%s\', \'%s\') is not None"' % ( sig, cache_dir) print(cmd) stat = os.system(cmd) assert stat == 0 # c print( "Skipping unit test, see https://bugs.launchpad.net/instant/+bug/518389" ) # Build and rebuild with generic signature object #sig = Sig("((test19_signature_module))") #tic() #module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) #assert module is not None #t1 = toc("(1) With signature") #tic() #module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) #assert module is not None #t2 = toc("(2) With signature") #assert t1 > t2 #tic() #module = import_module(sig, cache_dir) #assert module is not None #t3 = toc("(3) import_module") #assert t1 > t3 # Build and rebuild without modulename or signature tic() module = build_module(code=c_code, cache_dir=cache_dir) assert module is not None t1 = toc("(1) Without modulename or signature") tic() module = build_module(code=c_code, cache_dir=cache_dir) assert module is not None t2 = toc("(2) Without modulename or signature") assert t1 > t2
def compile_extension_module(code, module_name="", additional_declarations="", additional_system_headers=None, **instant_kwargs): """ Just In Time compile DOLFIN C++ code into a Python module. *Arguments* code C++ code which implements any function or C++ class. Any function or class available in the C++ DOLFIN namespace can be used and/or subclassed. All typemaps from the original Python interface are available, making it possible to interface with for example NumPy for Array<double/int> arguments. Source which is not wrapped in a dolfin namespace will be automatically wrapped. module_name Force a name of the module. If not set a name based on the hex representation of the code will be used. additional_declarations Additional SWIG declarations can be passed using this argument. additional_system_headers : System headers needed to compile the generated can be included using this argument. The headers are passed using a list of 'str' *Returns* The JIT compiled extension module *Examples of usage* The following toy example shows how one can use compiled extension modules to access low level PETSc routines: .. code-block:: python from numpy import arange code = ''' namespace dolfin { void PETSc_exp(std::shared_ptr<dolfin::PETScVector> vec) { Vec x = vec->vec(); assert(x); VecExp(x); } } ''' ext_module = compile_extension_module(code, additional_system_headers=["petscvec.h"]) comm = mpi_comm_world() vec = PETScVector(comm, 10) vec[:] = arange(10) print vec[-1] ext_module.PETSc_exp(vec) print vec[-1] """ # Check the provided arguments expect_arg(str, code, "first") expect_arg(str, module_name, "module_name") expect_arg(str, additional_declarations, "additional_declarations") additional_system_headers = \ expect_list_of(str, additional_system_headers, "additional_system_headers") # Check that the code does not use 'using namespace dolfin' if re.search("using\s+namespace\s+dolfin",code): cpp.dolfin_error("compilemodule.py", "ensure correct argument to compile_extension_module", "Do not use 'using namespace dolfin'. "\ "Include the code in namespace dolfin {...} instead") # Check if the code does not use namespace dolfin {...} if not re.search("namespace\s+dolfin\s*\{[\s\S]+\}", code): # Wrap and indet code in namespace dolfin codelines = ["namespace dolfin","{"] codelines += [" " + line for line in code.split("\n")] codelines += ["}"] code = "\n".join(codelines) # Create unique module name for this application run if module_name is "": module_name = "dolfin_compile_code_%s" % \ hashlib.md5(repr(code) + dolfin.__version__ + \ str(_interface_version)+\ additional_declarations +\ str(additional_system_headers)).hexdigest() # Extract dolfin dependencies and class names used_types, declared_types = parse_and_extract_type_info(code) # Add any bases of the declared types to used_types for declared_type, bases in declared_types.items(): used_types.update(bases) # Filter out dolfin types and add derived and bases for each type used_dolfin_types = [] for dolfin_type in dolfin_type_def: for used_type in used_types: if dolfin_type in used_type: # Add bases and derived types used_dolfin_types.extend(\ dolfin_type_def[dolfin_type]["bases"]) # Add dolfin type used_dolfin_types.append(dolfin_type) break # Generate dependency info dependencies = {} for dolfin_type in used_dolfin_types: if dolfin_type_def[dolfin_type]["submodule"] not in dependencies: dependencies[dolfin_type_def[dolfin_type]["submodule"]] = [] dependencies[dolfin_type_def[dolfin_type]["submodule"]].append(\ dolfin_type_def[dolfin_type]["header"]) # Need special treatment for template definitions in function/pre.i if "function" in dependencies: for dolfin_type in ["FunctionSpace", "Function"]: dependencies["function"].append(dolfin_type_def[dolfin_type]["header"]) # Add uint type if "common" in dependencies: dependencies["common"].append("dolfin/common/types.h") else: dependencies["common"] = ["dolfin/common/types.h"] # Sort the dependencies dependencies = sort_submodule_dependencies(dependencies, submodule_info) import_lines, headers_includes, file_dependencies = \ build_swig_import_info(dependencies, submodule_info, "dolfin.cpp.") # Extract header info dolfin_system_headers = [header for header in file_dependencies \ if not "pre.i" in header] # Check the handed import files interface_import_files = [] # Check cache compiled_module = instant.import_module(module_name) if compiled_module: # Check that the swig version of the compiled module is the same as # dolfin was compiled with check_swig_version(compiled_module) return compiled_module sys.stdout.flush() dolfin.info("Calling DOLFIN just-in-time (JIT) compiler, this may take some time.") # Configure instant and add additional system headers # Add dolfin system headers instant_kwargs["system_headers"] = ["cmath", "iostream","complex", "stdexcept","numpy/arrayobject.h", "memory", "dolfin/common/types.h", "dolfin/math/basic.h"] + \ instant_kwargs.get("system_headers", []) instant_kwargs["system_headers"] += dolfin_system_headers # Add user specified system headers instant_kwargs["system_headers"] += additional_system_headers # Add cmake packages instant_kwargs["cmake_packages"] = ["DOLFIN"] + \ instant_kwargs.get("cmake_packages", []) instant_kwargs["signature"] = module_name declaration_strs = {"additional_declarations":""} declaration_strs["dolfin_import_statement"] = \ "\n".join(import_lines) # Add any provided additional declarations if additional_declarations is not None: declaration_strs["additional_declarations"] += additional_declarations # Add any shared_ptr declarations declaration_strs["shared_ptr_declarations"] = \ extract_shared_ptr_declaration(declared_types, used_dolfin_types, \ shared_ptr_classes) # Compile extension module with instant compiled_module = instant.build_module(\ code = code, additional_declarations = _additional_declarations % declaration_strs, **instant_kwargs) sys.stdout.flush() # Check that the swig version of the compiled module is the same as # dolfin was compiled with check_swig_version(compiled_module) return compiled_module
def jit(ode, field_states=None, field_parameters=None, monitored=None, code_params=None, cppargs=None): """ Generate a goss::ODEParameterized from a gotran ode and JIT compile it Arguments: ---------- ode : gotran.ODE The gotran ode, either as an ODE or as an ODERepresentation field_states : list A list of state names, which should be treated as field states field_parameters : list A list of parameter names, which should be treated as field parameters monitored : list A list of names of intermediates of the ODE. Code for monitoring the intermediates will be generated. code_params : dict Parameters controling the code generation cppargs : str Default C++ argument passed to the C++ compiler """ # Code generators cgen = GossCodeGenerator(ode, field_states, field_parameters, monitored, code_params) cgen.params.class_code = True pgen = PythonCodeGenerator(cgen.params) # Create unique module name for this application run module_name = "goss_compiled_module_{0}_{1}".format(\ ode.name, hashlib.sha1((ode.signature() + \ repr(code_params) + \ repr(field_states) + \ repr(field_parameters) + \ repr(monitored) + \ #instant.get_swig_version() + \ instant.__version__ + \ gotran.__version__ + \ str(cppargs)).encode()).hexdigest()) # Check cache compiled_module = instant.import_module(module_name) if compiled_module: return getattr(compiled_module, cgen.name)() push_log_level(INFO) # Init state code python_code = pgen.init_states_code(ode) cpp_code = cgen.class_code() info("Calling GOSS just-in-time (JIT) compiler, this may take some "\ "time...") sys.stdout.flush() # Configure instant and add additional system headers instant_kwargs = configure_instant() instant_kwargs["cppargs"] = cppargs or instant_kwargs["cppargs"] instant_kwargs["cmake_packages"] = ["GOSS"] declaration_form = dict(\ ModelName = cgen.name, python_code = python_code, ) # Compile extension module with instant compiled_module = instant.build_module(\ code = cpp_code, additional_declarations = _additional_declarations.format(\ **declaration_form), signature = module_name, **instant_kwargs) info(" done") pop_log_level() sys.stdout.flush() # Return an instantiated class return getattr(compiled_module, cgen.name)()
""" system_headers = ['numpy/arrayobject.h', 'dolfin/function/Function.h', 'dolfin/function/FunctionSpace.h'] swigargs = ['-c++', '-fcompact', '-O', '-I.', '-small'] cmake_packages = ['DOLFIN'] sources = ["Probe.cpp"] source_dir = "Probe" include_dirs = [".", os.path.abspath("Probe")] compiled_module = instant.build_module( code=code, source_directory=source_dir, additional_declarations=additional_decl, system_headers=system_headers, include_dirs=include_dirs, swigargs=swigargs, sources=sources, cmake_packages=cmake_packages) mesh = UnitCubeMesh(10, 10, 10) V = FunctionSpace(mesh, 'CG', 1) x = numpy.array((0.5, 0.5, 0.5)) probe = compiled_module.Probe(x, V) # Just create some random data to be used for probing u0 = interpolate(Expression('x[0]'), V) probe.eval(u0) print "The number of probes is ", probe.number_of_eval_calls()
def compile(self): """ Compile the code. """ args = "" argtypes = [] cast_code = "" for name in sorted(self.__args.keys()): arg = self.__args[name] if len(args) > 0: args += ", " if arg == int: args += "int %s" % name argtypes.append(ctypes.c_int) elif arg == float: args += "double %s" % name argtypes.append(ctypes.c_double) elif arg == int_arr: args += "int* %s" % name argtypes.append( numpy.ctypeslib.ndpointer(ctypes.c_int, flags="C_CONTIGUOUS")) elif arg == long_arr: args += "long* %s" % name argtypes.append( numpy.ctypeslib.ndpointer(ctypes.c_long, flags="C_CONTIGUOUS")) elif arg == double_arr: args += "double* %s" % name argtypes.append( numpy.ctypeslib.ndpointer(ctypes.c_double, flags="C_CONTIGUOUS")) else: name_mangle = name while name_mangle in list(self.__args.keys()): name_mangle = "%s_" % name_mangle args += "void* %s" % name_mangle argtypes.append(ctypes.c_void_p) cast_code += " shared_ptr<%s> %s = (*((shared_ptr<%s>*)%s));\n" % \ (self.__boost_classes[arg], name, self.__boost_classes[arg], name_mangle) code = \ """ %s // Keep SWIG happy namespace dolfin { } using namespace dolfin; extern "C" { int code(%s) { %s %s return 0; } }""" % (self.__includes, args, cast_code, self.__code) mod = instant.build_module( code=code, cppargs=dolfin.parameters["form_compiler"]["cpp_optimize_flags"], lddargs="-ldolfin", include_dirs=self.__include_dirs, cmake_packages=["DOLFIN"]) path = os.path.dirname(mod.__file__) name = os.path.split(path)[-1] self.__lib = ctypes.cdll.LoadLibrary( os.path.join(path, "_%s.so" % name)) self.__lib.code.argtypes = argtypes self.__lib.code.restype = int return
def build_ufc_module(h_files, source_directory="", system_headers=None, \ **kwargs): """Build a python extension module from ufc compliant source code. The compiled module will be imported and returned by the function. @param h_files: The name(s) of the header files that should be compiled and included in the python extension module. @param source_directory: The directory where the source files reside. @param system_headers: Extra headers that will be #included in the generated wrapper file. Any additional keyword arguments are passed on to instant.build_module. """ # Check h_files argument if isinstance(h_files, str): h_files = [h_files] assert isinstance(h_files, list), "Provide a 'list' or a 'str' as 'h_files'." assert all(isinstance(f, str) for f in h_files), \ "Elements of 'h_files' must be 'str'." h_files2 = [os.path.join(source_directory, fn) for fn in h_files] for f in h_files2: if not os.path.isfile(f): raise IOError("The file '%s' does not exist." % f) # Check system_headers argument system_headers = system_headers or [] assert isinstance(system_headers, list), "Provide a 'list' as 'system_headers'" assert all(isinstance(header, str) for header in system_headers), \ "Elements of 'system_headers' must be 'str'." system_headers.append("memory") # Get the swig interface file declarations declarations = extract_declarations(h_files2) declarations += """ // SWIG version %inline %{ int get_swigversion() { return SWIGVERSION; } %} %pythoncode %{ tmp = hex(get_swigversion()) swigversion = "%d.%d.%d"%(tuple(map(int, [tmp[-5], tmp[-3], tmp[-2:]]))) del tmp, get_swigversion %} """ # Call instant and return module return instant.build_module(wrap_headers=h_files, source_directory=source_directory, additional_declarations=declarations, system_headers=system_headers, cmake_packages=["UFC"], **kwargs)
lz[pP-1] = lz[pP-1] + bdz; } //printf("%i %i %i %i %i\n",bdx,bdy,bdz,lxcell[0],lx[0]); if (dim==1) {ierr = DMDASetOwnershipRanges(sda, lx, NULL, NULL); CHKERRQ(ierr);} if (dim==2) {ierr = DMDASetOwnershipRanges(sda, lx, ly, NULL); CHKERRQ(ierr);} if (dim==3) {ierr = DMDASetOwnershipRanges(sda, lx, ly, lz); CHKERRQ(ierr);} PetscFree(lx); PetscFree(ly); PetscFree(lz); return 0; } """ decompfunction = instant.build_module( code=decompfunction_code, include_dirs=include_dirs, library_dirs=library_dirs, libraries=libraries, swig_include_dirs=swig_include_dirs).decompfunction class MeshBase(Mesh): def create_dof_map(self, elem, ci, b): swidth = elem.maxdegree() ndof = elem.ndofs() sizes = [] ndofs_per_cell = [ ] #this is the number of "unique" dofs per element ie 1 for DG0, 2 for DG1, 1 for CG1, 2 for CG2, etc. for i in xrange(self.ndim): nx = elem.get_nx(ci, i, self.nxs[b][i], self.bcs[i])
def test_timing(): #_t = None def tic(): global _t _t = -time.time() def toc(msg=""): t = time.time() + _t print("t = %f (%s)" % (t, msg)) return t c_code = """ double sum(double a, double b) { return a+b; } """ class Sig: def __init__(self, sig): self.sig = sig def signature(self): time.sleep(1.0) return self.sig def __hash__(self): time.sleep(0.5) return hash(self.sig) def __cmp__(self, other): if isinstance(other, Sig): return cmp(self.sig, other.sig) return -1 sig = Sig("((test18.py signature))") cache_dir = "test_cache" # Time a few builds tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t1 = toc("first build") tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t2 = toc("second build") tic() module = build_module(code=c_code, signature=sig, cache_dir=cache_dir) assert module is not None t3 = toc("third build") # Time importing tic() module = import_module(sig, cache_dir) assert module is not None t4 = toc("first import") tic() module = import_module(sig, cache_dir) assert module is not None t5 = toc("second import") assert t1 > 1 assert t2 < 1 and t2 > 0.4 assert t3 < 1 and t3 > 0.4 assert t4 < 1 and t4 > 0.4 assert t5 < 1 and t5 > 0.4