b0VIM 6.4ET kent-andkent-and-laptop~kent-and/Instant/Instant-0.9/src/Instant.py3210#"! Utps^txjJsf'JadsDC6 k G '   J )   ^ =  V 6  Z 5 d; `;nFrF   }EmG M321  """ def create_extension(self, **args): return 0 # all ok return 1 # Parsing of argurments detected errors print 'This is not the case for',file print 'Source files must have \'.c\' or \'.cpp\' suffix!' else: self.srcs.append(file) elif file.endswith('.c'): self.cppsrcs.append(file) if file.endswith('.cpp'): for file in self.sources: self.cppsrcs = [] self.srcs = [] # depending on the file-suffix (.c or .cpp). # sources has to be put in different variables, self.ifile_name = self.module+".i" self.logfile_name = self.module+".log" self.makefile_name = self.module+".mak" self.additional_declarations = dict[key] elif key == 'additional_declarations': self.additional_definitions = dict[key] elif key == 'additional_definitions': self.arrays = dict[key] elif key == 'arrays': self.object_files = dict[key] elif key == 'object_files': self.cppargs = dict[key] elif key == 'cppargs': self.library_dirs = dict[key] elif key == 'library_dirs': self.libraries = dict[key] elif key == 'libraries': self.include_dirs = dict[key] elif key == 'include_dirs': self.wrap_headers = dict[key] elif key == 'wrap_headers': self.local_headers = dict[key] elif key == 'local_headers': self.system_headers = dict[key] elif key == 'system_headers': self.sources = dict[key] elif key == 'sources': self.init_code = dict[key] elif key == 'init_code': self.swigopts = dict[key] elif key == 'swigopts': self.module = dict[key] elif key == 'module': self.code = dict[key] if key == 'code': for key in dict.keys(): """ A method for parsing arguments. """ def parse_args(self, dict): self.additional_declarations = "" self.additional_definitions = "" self.arrays = [] self.object_files = [] self.cppargs = '' self.library_dirs = [] self.libraries = [] self.include_dirs = ['-I.'] self.sources = [] self.wrap_headers = [] self.local_headers = [] self.system_headers = [] self.init_code = ' //Code for initialisation here' self.swigopts = '-I.' self.module = 'instant_swig_module' self.gen_setup = 1 }""" printf("No code supplied!\\n");{void f() self.code = """ """ Instant constructor """ def __init__(self): # Default values:class Instant:VERBOSE = 0import md5import stringimport commands import os, sys,re""">>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5)>>> add_func = inline(\"double add(double a, double b){ return a+b; }\")>>> from Instant import inlineA simple example: (see test1.py)it has to be inside a function or a similar C/C++ construct.The code can be either C or C++, but like when programming C or C++,an inline module, except you have to import the module manually.be created at runtime. For the user, it behaves somewhat likeBy using the class Instant a Python extension module can"""adDJ6sC! 2 x 3 & u t s r q p o @ 8 O N F 4 %   Q]2H return (includes,flags,libs, libdirs) raise OSError, "The pkg-config file %s does not exist" % pack else: for i in tmp: libdirs.append(i[2:]) tmp = string.split(commands.getoutput("pkg-config --libs-only-L %s " % pack )) for i in tmp: libs.append(i[2:]) tmp = string.split(commands.getoutput("pkg-config --libs-only-l %s " % pack )) for i in tmp: flags.append(i) tmp = string.split(commands.getoutput("pkg-config --cflags-only-other %s " % pack )) for i in tmp: includes.append(i[2:]) tmp = string.split(commands.getoutput("pkg-config --cflags-only-I %s " % pack )) if commands.getstatusoutput("pkg-config --exists %s " % pack)[0] == 0: # print commands.getstatusoutput("pkg-config --exists %s " % pack) for pack in packages: libdirs = [] libs = [] flags = [] includes = [] """ (includes, flags, libraries, libdirs) = header_and_libs_from_pkgconfig(list_of_packages) The usage is: This function returns list of include files, flags, libraries and library directories obtain from a pkgconfig file. """def header_and_libs_from_pkgconfig(*packages): return func_name exec("from inline_ext_numarray import %s as func_name"% func_name) init_code='import_array();', arrays = args_dict["arrays"]) sys.prefix + "/include" + "/numarray"][sys.platform=='win32']], include_dirs= [[sys.prefix + "/include/python" + sys.version[:3] + "/numarray", system_headers=["arrayobject.h"], cppargs='-O3', ext.create_extension(code=c_code, module="inline_ext_numarray", ret, func_name = func.split() func = c_code[:c_code.index('(')] ext = Instant() """ >>> sum_func(a) >>> a = numarray.arange(10000000); a = numarray.sin(a) >>> sum_func = inline_with_numarray(c_code, arrays = [['n1', 'array1']]) \"\"\" } return tmp; } tmp += array1[i]; for (int i=0; i>> c_code = \"\"\" >>> from Instant import inline_with_numarray >>> import time >>> import numarray Usage: The following example illustrates that. this function and the inline function is that C-arrays can be used. to inline one C function each time. The difference between the input is a valid C function. It is only possiblead x{O"}q4+ T  k j ^ F m K  [ H D *  } >   o\X>rq5edMLH4nR;.$#  {43 xTJ try:# print "Adding file ", filename, "to md5 sum " for filename in filenames: print filenames ''' modified based on Python24\Tools\Scripts\md5sum.py get the md5 value of filename ''' def getmd5sumfiles(self, filenames): return func_name[func_name.rindex(' ')+1:func_name.index('(')] print '... Done' if VERBOSE > 0: f.close() f.write(interface_string) f = open(self.ifile_name, 'w') """ % vars(self)%(code)s;%(typemaps)s%(wrap_headers_code2)s%(additional_declarations)s%(additional_definitions)s%%}%(init_code)s%%init%%{%%feature("autodoc", "1");%%}%(code)s%(wrap_headers_code1)s %(local_headers_code)s %(system_headers_code)s %(additional_definitions)s #include %%{%%feature("director");%%module (directors="1") %(module)s interface_string = """ self.typemaps = typemaps self.wrap_headers_code2 = "\n".join(['%%include "%s"' % header for header in self.wrap_headers]) self.wrap_headers_code1 = "\n".join(['#include "%s"' % header for header in self.wrap_headers]) self.local_headers_code = "\n".join(['#include "%s"' % header for header in self.local_headers]) self.system_headers_code = "\n".join(['#include <%s>' % header for header in self.system_headers]) typemaps += typemap""" % { 'n' : a[0] , 'ptv' : a[1], 'array' : a[2] }} $3 = (double*)pyarray->data; $2 = pyarray->dimensions; $1 = pyarray->nd; pyarray = (PyArrayObject*)$input; PyArrayObject* pyarray; } return NULL; ; PyErr_SetString(PyExc_TypeError, "Not a NumPy array"); if (!PyArray_Check($input)) { %%typemap(in) (int %(n)s,int* %(ptv)s,double* %(array)s){ typemap = """ elif (len(a) == 3): # n dimentional arrays, ie. matrices and tensors typemaps += typemap""" % { 'n' : a[0] , 'array' : a[1] }} $2 = (double*)pyarray->data; $1 = pyarray->dimensions[0]; pyarray = (PyArrayObject*)$input; PyArrayObject* pyarray; } return NULL; ; PyErr_SetString(PyExc_TypeError, "Not a NumPy array"); if (!PyArray_Check($input)) { %%typemap(in) (int %(n)s,double* %(array)s){ typemap = """ if (len(a) == 2): # 1 dimentional arrays, ie. vectors for a in self.arrays: if (len(self.arrays) > 0): typemaps = "" # create typemaps func_name = self.code[:self.code.index(')')+1] print "\nGenerating interface file \'"+ self.ifile_name +"\':" if VERBOSE > 0: """ - wrap_headers (A list of local headers that will be wrapped by SWIG) - local_headers (A list of local headers with declarations needed) - system_headers (A list of system headers with declarations needed) - init_code (Code to put in the init section of the interface file) - ifile_name (The SWIG input file) - code To generate an interface file it uses the following class-variables: Use this function to generate a SWIG interface file. """ def generate_Interfacefile(self): os.remove(file) if os.path.isfile(file): "_"+self.module+".so"]: self.module+".pyc", self.module+".py", self.module+".mak", self.module+".i", self.module+".log",ad$sgSI?>32pG2 Z 5   c ; $   w c Q -     < K 3 n="X9f$ mR <$>*"yxR >>> add_func = inline("double add(double a, double b){ return a+b; }") >>> from Instant import inline Usage: to inline one C function each time. the input is a valid C function. It is only possible It creates an extension module given that in Instant. This is a short wrapper around the create_extention function """def inline(c_code): ext.create_extension(**args) ext = Instant() """ - A list of the C arrays to be made from NumPy arrays. - B{arrays}: - If you want to compile the files yourself. NOT YET SUPPORTED. - B{object_files}: - A list of directories to search for libraries (C{-l}). - B{library_dirs}: - A list of libraries needed by the Instant extension. - B{libraries}: - Flags like C{-D}, C{-U}, etc. String. - B{cppargs}: - A list of source files to compile and link with the extension. - B{sources}: - A list of directories to search for header files. - B{include_dirs}: - A list of local header files that will be wrapped by SWIG. - B{wrap_headers}: - A list of local header files required by the Instant code. - B{local_headers}: - A list of system header files required by the Instant code. - B{system_headers}: - Code that should be executed when the Instant extension is imported. String. - B{init_code}: SWIG pointers.i library. String. - Options to swig, for instance C{-lpointers.i} to include the - B{swigopts}: - The name you want for the module (Default is 'instant_swig_module'.). String. - B{module}: - A Python string containing C or C++ function, class, .... - B{code}: ========== Arguments: an ordinary Python module. SWIG is used to generate code that can be compiled and used as Call this function to instantly create an extension module. in Instant. This is a small wrapper around the create_extension function """def create_extension(**args): return s s = s.replace(c, '') for c in ['[', ']', ',', '\'']: s = str(list)def list2str(list):# convert list values to string print 'Makefile', self.makefile_name, 'generated' if VERBOSE > 0: f.close() )) self.module list2str(self.library_dirs), list2str(self.include_dirs), list2str(self.cppsrcs), list2str(self.srcs), self.module, self.ifile_name, self.swigopts, self.cppargs, """ % (list2str(self.libraries), rm -f *_wrap* _%s.so *.o $(OBJ_FILES) *~clean:: python_cpp TARGET='$(TARGET)' \\ CFLAGS='$(CFLAGS) $(FLAGS)' \\ LIBS='$(LIBS) %s' \\ INCLUDES='$(INCLUDES) %s' \\ CPPSRCS='%s' \\ SRCS='%s' \\ SWIG='$(SWIG)' SWIGOPT='$(SWIGOPT)' \\ $(MAKE) -f '$(SWIGMAKEFILE)' INTERFACE='$(INTERFACE)' \\python::SWIGMAKEFILE = $(SWIGSRC)/Examples/MakefileINCLUDES = TARGET = %sINTERFACE = %sSWIGOPT = %sSWIG = swig FLAGS = %sLDPATH = LIBS = %s f.write(""" f = open(self.makefile_name, 'w') """ the supplied C/C++ code. uses SWIG's own Makefile to create an extension module ofad9f~\!R>6 ;  O -  A { 9 Q zf^-c32#" tR&d,  l"` w2 It creates an extension module given that in Instant. This is a short wrapper around the create_extention function """def inline_with_numarray(c_code, **args_dict): return func_name exec("from inline_ext_numeric import %s as func_name"% func_name) init_code='import_array();', arrays = args_dict["arrays"]) sys.prefix + "/include" + "/Numeric"][sys.platform=='win32']], include_dirs= [[sys.prefix + "/include/python" + sys.version[:3] + "/Numeric", system_headers=["arrayobject.h"], cppargs='-O3', ext.create_extension(code=c_code, module="inline_ext_numeric", ret, func_name = func.split() func = c_code[:c_code.index('(')] ext = Instant() """ >>> sum_func(a) >>> a = numpy.arange(10000000); a = numpy.sin(a) >>> sum_func = inline_with_numeric(c_code, arrays = [['n1', 'array1']]) \"\"\" } return tmp; } tmp += array1[i]; for (int i=0; i>> c_code = \"\"\" >>> from Instant import inline_with_numeric >>> import time >>> import numpy Usage: The following example illustrates that. this function and the inline function is that C-arrays can be used. to inline one C function each time. The difference between the input is a valid C function. It is only possible It creates an extension module given that in Instant. This is a short wrapper around the create_extention function """def inline_with_numeric(c_code, **args_dict): return func_name exec("from inline_ext_numpy import %s as func_name"% func_name) init_code='import_array();', arrays = args_dict["arrays"]) include_dirs= ["%s/numpy"% numpy.get_include()], system_headers=["arrayobject.h"], cppargs='-O3', ext.create_extension(code=c_code, module="inline_ext_numpy", import numpy ret, func_name = func.split() func = c_code[:c_code.index('(')] ext = Instant() """ >>> sum_func(a) >>> a = numpy.arange(10000000); a = numpy.sin(a) >>> sum_func = inline_with_numpy(c_code, arrays = [['n1', 'array1']]) \"\"\" } return tmp; } tmp += array1[i]; for (int i=0; i>> c_code = \"\"\" >>> from Instant import inline_with_numpy >>> import time >>> import numpy Usage: The following example illustrates that. this function and the inline function is that C-arrays can be used. to inline one C function each time. The difference between the input is a valid C function. It is only possible It creates an extension module given that in Instant. This is a short wrapper around the create_extention function """def inline_with_numpy(c_code, **args_dict): return func_name exec("from inline_ext import %s as func_name"% func_name) ext.create_extension(code=c_code, module="inline_ext") ret, func_name = func.split() func = c_code[:c_code.index('(')] ext = Instant() """ >>> print "The sum of 3 and 4.5 is ", add_func(3, 4.5)ad^uRQ>+U; E % m O  : ! m &  ] \ P D " kF G!{)a jihSG&!s@mH#"!  for file in [self.module+".log", if ( not gen_setup ) : """ Clean up files the current session. """ def clean(self): print 'cppargs',self.cppargs print 'cppsrcs',self.cppsrcs print 'srcs',self.srcs print 'sources',self.sources print 'include_dirs',self.include_dirs print 'wrap_headers',self.wrap_headers print 'local_headers',self.local_headers print 'system_headers',self.system_headers print 'init_code',self.init_code print 'swigopts',self.swigopts print 'module',self.module print 'code',self.code print 'DEBUG CODE:' """ print out all instance variable """ def debug(self): raise RuntimeError, "Could not find swig!\nYou can download swig from http://www.swig.org" else: # print "Module name is \'"+self.module+"\'" os.system("python " + self.module + "_setup.py install --install-platlib=.") os.system("python " + self.module + "_setup.py build_ext") self.generate_setup() else: os.remove(self.logfile_name) if VERBOSE == 9: os.system("make -f "+self.makefile_name+" &> "+self.logfile_name) os.system("make -f "+self.makefile_name+" clean") if os.path.isfile(self.makefile_name): self.generate_Makefile() if ( not self.gen_setup ): if (os.system("swig -version 2 > %s" % null ) == 0 ): null='/dev/null' else: null='nul' if sys.platform=='win32': if self.check_md5sum(): return 1 self.generate_Interfacefile() f.write("from %s import *"% self.module) f = open("__init__.py", 'w') os.chdir(self.module) os.mkdir(self.module) if not os.path.isdir(self.module): # self.debug() return print 'Nothing done!' if self.parse_args(args): """ - A list of the C arrays to be made from NumPy arrays. - B{arrays}: - If you want to compile the files yourself. NOT YET SUPPORTED. - B{object_files}: - A list of directories to search for libraries (C{-l}). - B{library_dirs}: - A list of libraries needed by the Instant extension. - B{libraries}: - Flags like C{-D}, C{-U}, etc. String. - B{cppargs}: - A list of source files to compile and link with the extension. - B{sources}: - A list of directories to search for header files. - B{include_dirs}: - A list of local header files that should be wrapped by SWIG. - B{wrap_headers}: - A list of local header files required by the Instant code. - B{local_headers}: - A list of system header files required by the Instant code. - B{system_headers}: - Code that should be executed when the Instant extension is imported. String. - B{init_code}: SWIG pointers.i library. String. - Options to swig, for instance C{-lpointers.i} to include the - B{swigopts}: - The name you want for the module (Default is 'instant_swig_module'.). String. - B{module}: - A Python string containing C or C++ function, class, .... - B{code}: ========== Arguments: an ordinary Python module. SWIG is used to generate code that can be compiled and used as Call this function to instantly create an extension module.adjiML2!` g 9 , x w Z M t G  | { z I s `  wn[ZYT6(tf4n0x" h@2(`9WLKJ) Generates a project dependent Makefile, which includes and """ def generate_Makefile(self): f.close() self.module, self.module, self.include_dirs, self.library_dirs, self.libraries )) self.cppsrcs, """ % (self.module, self.swigopts, self.ifile_name, library_dirs=%s, libraries=%s)]) include_dirs=%s, ext_modules = [Extension('_' + '%s', sources, setup(name = '%s', sources = %s os.system(swig_cmd)swig_cmd ='swig -python -c++ %s %s'name = '%s' from distutils.core import setup, Extensionimport os f.write(""" f = open(self.module+'_setup.py', 'w') self.cppsrcs.append( "%s_wrap.cxx" %self.module ) """ Generates a setup.py file """ def generate_setup(self): # return 0; # # return 0# os.system("md5sum " + self.ifile_name + " > " + self.module + ".md5") # else:# # # return 0 # os.system("md5sum " + self.ifile_name + " > " + self.module + ".md5") # else: # if ( current_md5sum == last_md5sum) : return 1 # last_md5sum = file.readline()# file = open(self.module + ".md5") # current_md5sum = pipe.readline() # pipe = os.popen("md5sum " + self.ifile_name) # if (os.path.isfile(self.module+".md5")):# """ # time the module was compiled. If it has changed then recompilation is necessary. # Check if the md5sum of the generated interface file has changed since the last# """ # def check_md5sum(self): return 0; return 0 self.writemd5sumfile(md5sum_files, self.module + ".md5") else: return 0 self.writemd5sumfile(md5sum_files, self.module + ".md5") else: if ( current_md5sum == last_md5sum) : return 1 last_md5sum = file.readline() file = open(self.module + ".md5") current_md5sum = self.getmd5sumfiles(md5sum_files ) if (os.path.isfile(self.module+".md5")): print md5sum_files for i in self.local_headers: md5sum_files.append(i) for i in self.wrap_headers : md5sum_files.append(i) for i in self.sources : md5sum_files.append(i) md5sum_files.append(self.ifile_name) md5sum_files = [] """ time the module was compiled. If it has changed then recompilation is necessary. Check if the md5sum of the generated interface file has changed since the last """ def check_md5sum(self): fp.close() fp.write(result) sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) except IOError, msg: fp = open(md5out, 'w') try: result=self.getmd5sumfiles(filenames) def writemd5sumfile(self, filenames, md5out=sys.stdout): return '%s %s\n' % (m.hexdigest().upper(), filename) fp.close() return None sys.stderr.write('%s: I/O error: %s\n' % (filename, msg)) except IOError, msg: m.update(data) break if not data: data = fp.read() while 1: try: m = md5.new() return None sys.stderr.write('%s: Can\'t open: %s\n' % (filename, msg)) except IOError, msg: fp = open(filename, 'rb')