[ { "hash": "68b8d1007e6b92f3fb4c218196a384c86039598d", "msg": "silly error of using == instead of =", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-14T07:27:47+00:00", "author_timezone": 0, "committer_date": "2002-01-14T07:27:47+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "9ff153264b133430790ff61bc1aec9cdd6260bf9" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 1, "lines": 2, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/catalog.py", "new_path": "weave/catalog.py", "filename": "catalog.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -40,7 +40,7 @@\n dumb = 0\n except ImportError:\n import dumb_shelve as shelve\n- dumb == 1\n+ dumb = 1\n \n #For testing...\n #import dumb_shelve as shelve\n", "added_lines": 1, "deleted_lines": 1, "source_code": "\"\"\" Track relationships between compiled extension functions & code fragments\n\n catalog keeps track of which compiled(or even standard) functions are \n related to which code fragments. It also stores these relationships\n to disk so they are remembered between Python sessions. When \n \n a = 1\n compiler.inline('printf(\"printed from C: %d\",a);',['a'] )\n \n is called, inline() first looks to see if it has seen the code \n 'printf(\"printed from C\");' before. If not, it calls \n \n catalog.get_functions('printf(\"printed from C: %d\", a);')\n \n which returns a list of all the function objects that have been compiled\n for the code fragment. Multiple functions can occur because the code\n could be compiled for different types for 'a' (although not likely in\n this case). The catalog first looks in its cache and quickly returns\n a list of the functions if possible. If the cache lookup fails, it then\n looks through possibly multiple catalog files on disk and fills its\n cache with all the functions that match the code fragment. \n \n In case where the code fragment hasn't been compiled, inline() compiles\n the code and then adds it to the catalog:\n \n function = \n catalog.add_function('printf(\"printed from C: %d\", a);',function)\n \n add_function() adds function to the front of the cache. function,\n along with the path information to its module, are also stored in a\n persistent catalog for future use by python sessions. \n\"\"\" \n\nimport os,sys,string\nimport pickle\n\ntry:\n import dbhash\n import shelve\n dumb = 0\nexcept ImportError:\n import dumb_shelve as shelve\n dumb = 1\n\n#For testing...\n#import dumb_shelve as shelve\n#dumb = 1\n\n#import shelve\n#dumb = 0\n \ndef getmodule(object):\n \"\"\" Discover the name of the module where object was defined.\n \n This is an augmented version of inspect.getmodule that can discover \n the parent module for extension functions.\n \"\"\"\n import inspect\n value = inspect.getmodule(object)\n if value is None:\n #walk trough all modules looking for function\n for name,mod in sys.modules.items():\n # try except used because of some comparison failures\n # in wxPoint code. Need to review this\n try:\n if mod and object in mod.__dict__.values():\n value = mod\n # if it is a built-in module, keep looking to see\n # if a non-builtin also has it. Otherwise quit and\n # consider the module found. (ain't perfect, but will \n # have to do for now).\n if string.find('(built-in)',str(mod)) is -1:\n break\n \n except (TypeError, KeyError):\n pass \n return value\n\ndef expr_to_filename(expr):\n \"\"\" Convert an arbitrary expr string to a valid file name.\n \n The name is based on the md5 check sum for the string and\n Something that was a little more human readable would be \n nice, but the computer doesn't seem to care.\n \"\"\"\n import md5\n base = 'sc_'\n return base + md5.new(expr).hexdigest()\n\ndef unique_file(d,expr):\n \"\"\" Generate a unqiue file name based on expr in directory d\n \n This is meant for use with building extension modules, so\n a file name is considered unique if none of the following\n extension '.cpp','.o','.so','module.so','.py', or '.pyd'\n exists in directory d. The fully qualified path to the\n new name is returned. You'll need to append your own\n extension to it before creating files.\n \"\"\"\n files = os.listdir(d)\n #base = 'scipy_compile'\n base = expr_to_filename(expr)\n for i in range(1000000):\n fname = base + `i`\n if not (fname+'.cpp' in files or\n fname+'.o' in files or\n fname+'.so' in files or\n fname+'module.so' in files or\n fname+'.py' in files or\n fname+'.pyd' in files):\n break\n return os.path.join(d,fname)\n \ndef default_dir():\n \"\"\" Return a default location to store compiled files and catalogs.\n \n XX is the Python version number in all paths listed below\n On windows, the default location is the temporary directory\n returned by gettempdir()/pythonXX.\n \n On Unix, ~/.pythonXX_compiled is the default location. If it doesn't\n exist, it is created. The directory is marked rwx------.\n \n If for some reason it isn't possible to build a default directory\n in the user's home, /tmp/_pythonXX_compiled is used. If it \n doesn't exist, it is created. The directory is marked rwx------\n to try and keep people from being able to sneak a bad module\n in on you. \n \"\"\"\n import tempfile \n python_name = \"python%d%d_compiled\" % tuple(sys.version_info[:2]) \n if sys.platform != 'win32':\n try:\n path = os.path.join(os.environ['HOME'],'.' + python_name)\n except KeyError:\n temp_dir = `os.getuid()` + '_' + python_name\n path = os.path.join(tempfile.gettempdir(),temp_dir) \n else:\n path = os.path.join(tempfile.gettempdir(),python_name)\n \n if not os.path.exists(path):\n os.mkdir(path)\n os.chmod(path,0700) # make it only accessible by this user.\n if not os.access(path,os.W_OK):\n print 'warning: default directory is not write accessible.'\n print 'defualt:', path\n return path\n\ndef intermediate_dir():\n \"\"\" Location in temp dir for storing .cpp and .o files during\n builds.\n \"\"\"\n import tempfile \n python_name = \"python%d%d_intermediate\" % tuple(sys.version_info[:2]) \n path = os.path.join(tempfile.gettempdir(),python_name)\n if not os.path.exists(path):\n os.mkdir(path)\n return path\n \ndef default_temp_dir():\n path = os.path.join(default_dir(),'temp')\n if not os.path.exists(path):\n os.mkdir(path)\n os.chmod(path,0700) # make it only accessible by this user.\n if not os.access(path,os.W_OK):\n print 'warning: default directory is not write accessible.'\n print 'defualt:', path\n return path\n\n \ndef os_dependent_catalog_name():\n \"\"\" Generate catalog name dependent on OS and Python version being used.\n \n This allows multiple platforms to have catalog files in the\n same directory without stepping on each other. For now, it \n bases the name of the value returned by sys.platform and the\n version of python being run. If this isn't enough to descriminate\n on some platforms, we can try to add other info. It has \n occured to me that if we get fancy enough to optimize for different\n architectures, then chip type might be added to the catalog name also.\n \"\"\"\n version = '%d%d' % sys.version_info[:2]\n return sys.platform+version+'compiled_catalog'\n \ndef catalog_path(module_path):\n \"\"\" Return the full path name for the catalog file in the given directory.\n \n module_path can either be a file name or a path name. If it is a \n file name, the catalog file name in its parent directory is returned.\n If it is a directory, the catalog file in that directory is returned.\n\n If module_path doesn't exist, None is returned. Note though, that the\n catalog file does *not* have to exist, only its parent. '~', shell\n variables, and relative ('.' and '..') paths are all acceptable.\n \n catalog file names are os dependent (based on sys.platform), so this \n should support multiple platforms sharing the same disk space \n (NFS mounts). See os_dependent_catalog_name() for more info.\n \"\"\"\n module_path = os.path.expanduser(module_path)\n module_path = os.path.expandvars(module_path)\n module_path = os.path.abspath(module_path)\n if not os.path.exists(module_path):\n catalog_file = None\n elif not os.path.isdir(module_path):\n module_path,dummy = os.path.split(module_path)\n catalog_file = os.path.join(module_path,os_dependent_catalog_name())\n else: \n catalog_file = os.path.join(module_path,os_dependent_catalog_name())\n return catalog_file\n\ndef get_catalog(module_path,mode='r'):\n \"\"\" Return a function catalog (shelve object) from the path module_path\n\n If module_path is a directory, the function catalog returned is\n from that directory. If module_path is an actual module_name,\n then the function catalog returned is from its parent directory.\n mode uses the standard 'c' = create, 'n' = new, 'r' = read, \n 'w' = write file open modes available for anydbm databases.\n \n Well... it should be. Stuck with dumbdbm for now and the modes\n almost don't matter. We do some checking for 'r' mode, but that\n is about it.\n \n See catalog_path() for more information on module_path.\n \"\"\"\n if mode not in ['c','r','w','n']:\n msg = \" mode must be 'c', 'n', 'r', or 'w'. See anydbm for more info\"\n raise ValueError, msg\n catalog_file = catalog_path(module_path)\n try:\n # code reliant on the fact that we are using dumbdbm\n if dumb and mode == 'r' and not os.path.exists(catalog_file+'.dat'):\n sh = None\n else:\n sh = shelve.open(catalog_file,mode)\n except: # not sure how to pin down which error to catch yet\n sh = None\n return sh\n\nclass catalog:\n \"\"\" Stores information about compiled functions both in cache and on disk.\n \n catalog stores (code, list_of_function) pairs so that all the functions\n that have been compiled for code are available for calling (usually in\n inline or blitz).\n \n catalog keeps a dictionary of previously accessed code values cached \n for quick access. It also handles the looking up of functions compiled \n in previously called Python sessions on disk in function catalogs. \n catalog searches the directories in the PYTHONCOMPILED environment \n variable in order loading functions that correspond to the given code \n fragment. A default directory is also searched for catalog functions. \n On unix, the default directory is usually '~/.pythonxx_compiled' where \n xx is the version of Python used. On windows, it is the directory \n returned by temfile.gettempdir(). Functions closer to the front are of \n the variable list are guaranteed to be closer to the front of the \n function list so that they will be called first. See \n get_cataloged_functions() for more info on how the search order is \n traversed.\n \n Catalog also handles storing information about compiled functions to\n a catalog. When writing this information, the first writable catalog\n file in PYTHONCOMPILED path is used. If a writable catalog is not\n found, it is written to the catalog in the default directory. This\n directory should always be writable.\n \"\"\"\n def __init__(self,user_path_list=None):\n \"\"\" Create a catalog for storing/searching for compiled functions. \n \n user_path_list contains directories that should be searched \n first for function catalogs. They will come before the path\n entries in the PYTHONCOMPILED environment varilable.\n \"\"\"\n if type(user_path_list) == type('string'):\n self.user_path_list = [user_path_list]\n elif user_path_list:\n self.user_path_list = user_path_list\n else:\n self.user_path_list = []\n self.cache = {}\n self.module_dir = None\n self.paths_added = 0\n \n def set_module_directory(self,module_dir):\n \"\"\" Set the path that will replace 'MODULE' in catalog searches.\n \n You should call clear_module_directory() when your finished\n working with it.\n \"\"\"\n self.module_dir = module_dir\n def get_module_directory(self):\n \"\"\" Return the path used to replace the 'MODULE' in searches.\n \"\"\"\n return self.module_dir\n def clear_module_directory(self):\n \"\"\" Reset 'MODULE' path to None so that it is ignored in searches. \n \"\"\"\n self.module_dir = None\n \n def get_environ_path(self):\n \"\"\" Return list of paths from 'PYTHONCOMPILED' environment variable.\n \n On Unix the path in PYTHONCOMPILED is a ':' separated list of\n directories. On Windows, a ';' separated list is used. \n \"\"\"\n paths = []\n if os.environ.has_key('PYTHONCOMPILED'):\n path_string = os.environ['PYTHONCOMPILED'] \n if sys.platform == 'win32':\n #probably should also look in registry\n paths = path_string.split(';')\n else: \n paths = path_string.split(':')\n return paths \n\n def build_search_order(self):\n \"\"\" Returns a list of paths that are searched for catalogs. \n \n Values specified in the catalog constructor are searched first,\n then values found in the PYTHONCOMPILED environment variable.\n The directory returned by default_dir() is always returned at\n the end of the list.\n \n There is a 'magic' path name called 'MODULE' that is replaced\n by the directory defined by set_module_directory(). If the\n module directory hasn't been set, 'MODULE' is ignored.\n \"\"\"\n \n paths = self.user_path_list + self.get_environ_path()\n search_order = []\n for path in paths:\n if path == 'MODULE':\n if self.module_dir:\n search_order.append(self.module_dir)\n else:\n search_order.append(path)\n search_order.append(default_dir())\n return search_order\n\n def get_catalog_files(self):\n \"\"\" Returns catalog file list in correct search order.\n \n Some of the catalog files may not currently exists.\n However, all will be valid locations for a catalog\n to be created (if you have write permission).\n \"\"\"\n files = map(catalog_path,self.build_search_order())\n files = filter(lambda x: x is not None,files)\n return files\n\n def get_existing_files(self):\n \"\"\" Returns all existing catalog file list in correct search order.\n \"\"\"\n files = self.get_catalog_files()\n # open every stinking file to check if it exists.\n # This is because anydbm doesn't provide a consistent naming \n # convention across platforms for its files \n existing_files = []\n for file in files:\n if get_catalog(os.path.dirname(file),'r') is not None:\n existing_files.append(file)\n # This is the non-portable (and much faster) old code\n #existing_files = filter(os.path.exists,files)\n return existing_files\n\n def get_writable_file(self,existing_only=0):\n \"\"\" Return the name of the first writable catalog file.\n \n Its parent directory must also be writable. This is so that\n compiled modules can be written to the same directory.\n \"\"\"\n # note: both file and its parent directory must be writeable\n if existing_only:\n files = self.get_existing_files()\n else:\n files = self.get_catalog_files()\n # filter for (file exists and is writable) OR directory is writable\n def file_test(x):\n from os import access, F_OK, W_OK\n return (access(x,F_OK) and access(x,W_OK) or\n access(os.path.dirname(x),W_OK))\n writable = filter(file_test,files)\n if writable:\n file = writable[0]\n else:\n file = None\n return file\n \n def get_writable_dir(self):\n \"\"\" Return the parent directory of first writable catalog file.\n \n The returned directory has write access.\n \"\"\"\n return os.path.dirname(self.get_writable_file())\n \n def unique_module_name(self,code,module_dir=None):\n \"\"\" Return full path to unique file name that in writable location.\n \n The directory for the file is the first writable directory in \n the catalog search path. The unique file name is derived from\n the code fragment. If, module_dir is specified, it is used\n to replace 'MODULE' in the search path.\n \"\"\"\n if module_dir is not None:\n self.set_module_directory(module_dir)\n try:\n d = self.get_writable_dir()\n finally:\n if module_dir is not None:\n self.clear_module_directory()\n return unique_file(d,code)\n\n def path_key(self,code):\n \"\"\" Return key for path information for functions associated with code.\n \"\"\"\n return '__path__' + code\n \n def configure_path(self,cat,code):\n \"\"\" Add the python path for the given code to the sys.path\n \n unconfigure_path() should be called as soon as possible after\n imports associated with code are finished so that sys.path \n is restored to normal.\n \"\"\"\n try:\n paths = cat[self.path_key(code)]\n self.paths_added = len(paths)\n sys.path = paths + sys.path\n except:\n self.paths_added = 0 \n \n def unconfigure_path(self):\n \"\"\" Restores sys.path to normal after calls to configure_path()\n \n Remove the previously added paths from sys.path\n \"\"\"\n sys.path = sys.path[self.paths_added:]\n self.paths_added = 0\n\n def get_cataloged_functions(self,code):\n \"\"\" Load all functions associated with code from catalog search path.\n \n Sometimes there can be trouble loading a function listed in a\n catalog file because the actual module that holds the function \n has been moved or deleted. When this happens, that catalog file\n is \"repaired\", meaning the entire entry for this function is \n removed from the file. This only affects the catalog file that\n has problems -- not the others in the search path.\n \n The \"repair\" behavior may not be needed, but I'll keep it for now.\n \"\"\"\n mode = 'r'\n cat = None\n function_list = []\n for path in self.build_search_order():\n cat = get_catalog(path,mode)\n if cat is not None and cat.has_key(code):\n # set up the python path so that modules for this\n # function can be loaded.\n self.configure_path(cat,code)\n try: \n function_list += cat[code]\n except: #SystemError and ImportError so far seen \n # problems loading a function from the catalog. Try to\n # repair the cause.\n cat.close()\n self.repair_catalog(path,code)\n self.unconfigure_path() \n return function_list\n\n\n def repair_catalog(self,catalog_path,code):\n \"\"\" Remove entry for code from catalog_path\n \n Occasionally catalog entries could get corrupted. An example\n would be when a module that had functions in the catalog was\n deleted or moved on the disk. The best current repair method is \n just to trash the entire catalog entry for this piece of code. \n This may loose function entries that are valid, but thats life.\n \n catalog_path must be writable for repair. If it isn't, the\n function exists with a warning. \n \"\"\"\n writable_cat = None\n if not os.path.exists(catalog_path):\n return\n try:\n writable_cat = get_catalog(catalog_path,'w')\n except:\n print 'warning: unable to repair catalog entry\\n %s\\n in\\n %s' % \\\n (code,catalog_path)\n return \n if writable_cat.has_key(code):\n print 'repairing catalog by removing key'\n del writable_cat[code]\n \n # it is possible that the path key doesn't exist (if the function registered\n # was a built-in function), so we have to check if the path exists before\n # arbitrarily deleting it.\n path_key = self.path_key(code) \n if writable_cat.has_key(path_key):\n del writable_cat[path_key] \n \n def get_functions_fast(self,code):\n \"\"\" Return list of functions for code from the cache.\n \n Return an empty list if the code entry is not found.\n \"\"\"\n return self.cache.get(code,[])\n \n def get_functions(self,code,module_dir=None):\n \"\"\" Return the list of functions associated with this code fragment.\n \n The cache is first searched for the function. If an entry\n in the cache is not found, then catalog files on disk are \n searched for the entry. This is slooooow, but only happens\n once per code object. All the functions found in catalog files\n on a cache miss are loaded into the cache to speed up future calls.\n The search order is as follows:\n \n 1. user specified path (from catalog initialization)\n 2. directories from the PYTHONCOMPILED environment variable\n 3. The temporary directory on your platform.\n\n The path specified by module_dir will replace the 'MODULE' \n place holder in the catalog search path. See build_search_order()\n for more info on the search path. \n \"\"\" \n # Fast!! try cache first.\n if self.cache.has_key(code):\n return self.cache[code]\n \n # 2. Slow!! read previously compiled functions from disk.\n try:\n self.set_module_directory(module_dir)\n function_list = self.get_cataloged_functions(code)\n # put function_list in cache to save future lookups.\n if function_list:\n self.cache[code] = function_list\n # return function_list, empty or otherwise.\n finally:\n self.clear_module_directory()\n return function_list\n\n def add_function(self,code,function,module_dir=None):\n \"\"\" Adds a function to the catalog.\n \n The function is added to the cache as well as the first\n writable file catalog found in the search path. If no\n code entry exists in the cache, the on disk catalogs\n are loaded into the cache and function is added to the\n beginning of the function list.\n \n The path specified by module_dir will replace the 'MODULE' \n place holder in the catalog search path. See build_search_order()\n for more info on the search path. \n \"\"\" \n\n # 1. put it in the cache.\n if self.cache.has_key(code):\n if function not in self.cache[code]:\n self.cache[code].insert(0,function)\n else:\n # if it is in the cache, then it is also\n # been persisted \n return\n else: \n # Load functions and put this one up front\n self.cache[code] = self.get_functions(code) \n self.fast_cache(code,function)\n # 2. Store the function entry to disk. \n try:\n self.set_module_directory(module_dir)\n self.add_function_persistent(code,function)\n finally:\n self.clear_module_directory()\n \n def add_function_persistent(self,code,function):\n \"\"\" Store the code->function relationship to disk.\n \n Two pieces of information are needed for loading functions\n from disk -- the function pickle (which conveniently stores\n the module name, etc.) and the path to its module's directory.\n The latter is needed so that the function can be loaded no\n matter what the user's Python path is.\n \"\"\" \n # add function to data in first writable catalog\n mode = 'c' # create if doesn't exist, otherwise, use existing\n cat_dir = self.get_writable_dir()\n cat = get_catalog(cat_dir,mode)\n if cat is None:\n cat_dir = default_dir()\n cat = get_catalog(cat_dir,mode)\n if cat is None:\n cat_dir = default_dir() \n cat_file = catalog_path(cat_dir)\n print 'problems with default catalog -- removing'\n import glob\n files = glob.glob(cat_file+'*')\n for f in files:\n os.remove(f)\n cat = get_catalog(cat_dir,mode)\n if cat is None:\n raise ValueError, 'Failed to access a catalog for storing functions' \n # Prabhu was getting some corrupt catalog errors. I'll put a try/except\n # to protect against this, but should really try and track down the issue.\n function_list = [function]\n try:\n function_list = function_list + cat.get(code,[])\n except pickle.UnpicklingError:\n pass\n cat[code] = function_list\n # now add needed path information for loading function\n module = getmodule(function)\n try:\n # built in modules don't have the __file__ extension, so this\n # will fail. Just pass in this case since path additions aren't\n # needed for built-in modules.\n mod_path,f=os.path.split(os.path.abspath(module.__file__))\n pkey = self.path_key(code)\n cat[pkey] = [mod_path] + cat.get(pkey,[])\n except:\n pass\n\n def fast_cache(self,code,function):\n \"\"\" Move function to the front of the cache entry for code\n \n If future calls to the function have the same type signature,\n this will speed up access significantly because the first\n function call is correct.\n \n Note: The cache added to the inline_tools module is significantly\n faster than always calling get_functions, so this isn't\n as necessary as it used to be. Still, it's probably worth\n doing. \n \"\"\"\n try:\n if self.cache[code][0] == function:\n return\n except: # KeyError, IndexError \n pass\n try:\n self.cache[code].remove(function)\n except ValueError:\n pass\n # put new function at the beginning of the list to search.\n self.cache[code].insert(0,function)\n \ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "\"\"\" Track relationships between compiled extension functions & code fragments\n\n catalog keeps track of which compiled(or even standard) functions are \n related to which code fragments. It also stores these relationships\n to disk so they are remembered between Python sessions. When \n \n a = 1\n compiler.inline('printf(\"printed from C: %d\",a);',['a'] )\n \n is called, inline() first looks to see if it has seen the code \n 'printf(\"printed from C\");' before. If not, it calls \n \n catalog.get_functions('printf(\"printed from C: %d\", a);')\n \n which returns a list of all the function objects that have been compiled\n for the code fragment. Multiple functions can occur because the code\n could be compiled for different types for 'a' (although not likely in\n this case). The catalog first looks in its cache and quickly returns\n a list of the functions if possible. If the cache lookup fails, it then\n looks through possibly multiple catalog files on disk and fills its\n cache with all the functions that match the code fragment. \n \n In case where the code fragment hasn't been compiled, inline() compiles\n the code and then adds it to the catalog:\n \n function = \n catalog.add_function('printf(\"printed from C: %d\", a);',function)\n \n add_function() adds function to the front of the cache. function,\n along with the path information to its module, are also stored in a\n persistent catalog for future use by python sessions. \n\"\"\" \n\nimport os,sys,string\nimport pickle\n\ntry:\n import dbhash\n import shelve\n dumb = 0\nexcept ImportError:\n import dumb_shelve as shelve\n dumb == 1\n\n#For testing...\n#import dumb_shelve as shelve\n#dumb = 1\n\n#import shelve\n#dumb = 0\n \ndef getmodule(object):\n \"\"\" Discover the name of the module where object was defined.\n \n This is an augmented version of inspect.getmodule that can discover \n the parent module for extension functions.\n \"\"\"\n import inspect\n value = inspect.getmodule(object)\n if value is None:\n #walk trough all modules looking for function\n for name,mod in sys.modules.items():\n # try except used because of some comparison failures\n # in wxPoint code. Need to review this\n try:\n if mod and object in mod.__dict__.values():\n value = mod\n # if it is a built-in module, keep looking to see\n # if a non-builtin also has it. Otherwise quit and\n # consider the module found. (ain't perfect, but will \n # have to do for now).\n if string.find('(built-in)',str(mod)) is -1:\n break\n \n except (TypeError, KeyError):\n pass \n return value\n\ndef expr_to_filename(expr):\n \"\"\" Convert an arbitrary expr string to a valid file name.\n \n The name is based on the md5 check sum for the string and\n Something that was a little more human readable would be \n nice, but the computer doesn't seem to care.\n \"\"\"\n import md5\n base = 'sc_'\n return base + md5.new(expr).hexdigest()\n\ndef unique_file(d,expr):\n \"\"\" Generate a unqiue file name based on expr in directory d\n \n This is meant for use with building extension modules, so\n a file name is considered unique if none of the following\n extension '.cpp','.o','.so','module.so','.py', or '.pyd'\n exists in directory d. The fully qualified path to the\n new name is returned. You'll need to append your own\n extension to it before creating files.\n \"\"\"\n files = os.listdir(d)\n #base = 'scipy_compile'\n base = expr_to_filename(expr)\n for i in range(1000000):\n fname = base + `i`\n if not (fname+'.cpp' in files or\n fname+'.o' in files or\n fname+'.so' in files or\n fname+'module.so' in files or\n fname+'.py' in files or\n fname+'.pyd' in files):\n break\n return os.path.join(d,fname)\n \ndef default_dir():\n \"\"\" Return a default location to store compiled files and catalogs.\n \n XX is the Python version number in all paths listed below\n On windows, the default location is the temporary directory\n returned by gettempdir()/pythonXX.\n \n On Unix, ~/.pythonXX_compiled is the default location. If it doesn't\n exist, it is created. The directory is marked rwx------.\n \n If for some reason it isn't possible to build a default directory\n in the user's home, /tmp/_pythonXX_compiled is used. If it \n doesn't exist, it is created. The directory is marked rwx------\n to try and keep people from being able to sneak a bad module\n in on you. \n \"\"\"\n import tempfile \n python_name = \"python%d%d_compiled\" % tuple(sys.version_info[:2]) \n if sys.platform != 'win32':\n try:\n path = os.path.join(os.environ['HOME'],'.' + python_name)\n except KeyError:\n temp_dir = `os.getuid()` + '_' + python_name\n path = os.path.join(tempfile.gettempdir(),temp_dir) \n else:\n path = os.path.join(tempfile.gettempdir(),python_name)\n \n if not os.path.exists(path):\n os.mkdir(path)\n os.chmod(path,0700) # make it only accessible by this user.\n if not os.access(path,os.W_OK):\n print 'warning: default directory is not write accessible.'\n print 'defualt:', path\n return path\n\ndef intermediate_dir():\n \"\"\" Location in temp dir for storing .cpp and .o files during\n builds.\n \"\"\"\n import tempfile \n python_name = \"python%d%d_intermediate\" % tuple(sys.version_info[:2]) \n path = os.path.join(tempfile.gettempdir(),python_name)\n if not os.path.exists(path):\n os.mkdir(path)\n return path\n \ndef default_temp_dir():\n path = os.path.join(default_dir(),'temp')\n if not os.path.exists(path):\n os.mkdir(path)\n os.chmod(path,0700) # make it only accessible by this user.\n if not os.access(path,os.W_OK):\n print 'warning: default directory is not write accessible.'\n print 'defualt:', path\n return path\n\n \ndef os_dependent_catalog_name():\n \"\"\" Generate catalog name dependent on OS and Python version being used.\n \n This allows multiple platforms to have catalog files in the\n same directory without stepping on each other. For now, it \n bases the name of the value returned by sys.platform and the\n version of python being run. If this isn't enough to descriminate\n on some platforms, we can try to add other info. It has \n occured to me that if we get fancy enough to optimize for different\n architectures, then chip type might be added to the catalog name also.\n \"\"\"\n version = '%d%d' % sys.version_info[:2]\n return sys.platform+version+'compiled_catalog'\n \ndef catalog_path(module_path):\n \"\"\" Return the full path name for the catalog file in the given directory.\n \n module_path can either be a file name or a path name. If it is a \n file name, the catalog file name in its parent directory is returned.\n If it is a directory, the catalog file in that directory is returned.\n\n If module_path doesn't exist, None is returned. Note though, that the\n catalog file does *not* have to exist, only its parent. '~', shell\n variables, and relative ('.' and '..') paths are all acceptable.\n \n catalog file names are os dependent (based on sys.platform), so this \n should support multiple platforms sharing the same disk space \n (NFS mounts). See os_dependent_catalog_name() for more info.\n \"\"\"\n module_path = os.path.expanduser(module_path)\n module_path = os.path.expandvars(module_path)\n module_path = os.path.abspath(module_path)\n if not os.path.exists(module_path):\n catalog_file = None\n elif not os.path.isdir(module_path):\n module_path,dummy = os.path.split(module_path)\n catalog_file = os.path.join(module_path,os_dependent_catalog_name())\n else: \n catalog_file = os.path.join(module_path,os_dependent_catalog_name())\n return catalog_file\n\ndef get_catalog(module_path,mode='r'):\n \"\"\" Return a function catalog (shelve object) from the path module_path\n\n If module_path is a directory, the function catalog returned is\n from that directory. If module_path is an actual module_name,\n then the function catalog returned is from its parent directory.\n mode uses the standard 'c' = create, 'n' = new, 'r' = read, \n 'w' = write file open modes available for anydbm databases.\n \n Well... it should be. Stuck with dumbdbm for now and the modes\n almost don't matter. We do some checking for 'r' mode, but that\n is about it.\n \n See catalog_path() for more information on module_path.\n \"\"\"\n if mode not in ['c','r','w','n']:\n msg = \" mode must be 'c', 'n', 'r', or 'w'. See anydbm for more info\"\n raise ValueError, msg\n catalog_file = catalog_path(module_path)\n try:\n # code reliant on the fact that we are using dumbdbm\n if dumb and mode == 'r' and not os.path.exists(catalog_file+'.dat'):\n sh = None\n else:\n sh = shelve.open(catalog_file,mode)\n except: # not sure how to pin down which error to catch yet\n sh = None\n return sh\n\nclass catalog:\n \"\"\" Stores information about compiled functions both in cache and on disk.\n \n catalog stores (code, list_of_function) pairs so that all the functions\n that have been compiled for code are available for calling (usually in\n inline or blitz).\n \n catalog keeps a dictionary of previously accessed code values cached \n for quick access. It also handles the looking up of functions compiled \n in previously called Python sessions on disk in function catalogs. \n catalog searches the directories in the PYTHONCOMPILED environment \n variable in order loading functions that correspond to the given code \n fragment. A default directory is also searched for catalog functions. \n On unix, the default directory is usually '~/.pythonxx_compiled' where \n xx is the version of Python used. On windows, it is the directory \n returned by temfile.gettempdir(). Functions closer to the front are of \n the variable list are guaranteed to be closer to the front of the \n function list so that they will be called first. See \n get_cataloged_functions() for more info on how the search order is \n traversed.\n \n Catalog also handles storing information about compiled functions to\n a catalog. When writing this information, the first writable catalog\n file in PYTHONCOMPILED path is used. If a writable catalog is not\n found, it is written to the catalog in the default directory. This\n directory should always be writable.\n \"\"\"\n def __init__(self,user_path_list=None):\n \"\"\" Create a catalog for storing/searching for compiled functions. \n \n user_path_list contains directories that should be searched \n first for function catalogs. They will come before the path\n entries in the PYTHONCOMPILED environment varilable.\n \"\"\"\n if type(user_path_list) == type('string'):\n self.user_path_list = [user_path_list]\n elif user_path_list:\n self.user_path_list = user_path_list\n else:\n self.user_path_list = []\n self.cache = {}\n self.module_dir = None\n self.paths_added = 0\n \n def set_module_directory(self,module_dir):\n \"\"\" Set the path that will replace 'MODULE' in catalog searches.\n \n You should call clear_module_directory() when your finished\n working with it.\n \"\"\"\n self.module_dir = module_dir\n def get_module_directory(self):\n \"\"\" Return the path used to replace the 'MODULE' in searches.\n \"\"\"\n return self.module_dir\n def clear_module_directory(self):\n \"\"\" Reset 'MODULE' path to None so that it is ignored in searches. \n \"\"\"\n self.module_dir = None\n \n def get_environ_path(self):\n \"\"\" Return list of paths from 'PYTHONCOMPILED' environment variable.\n \n On Unix the path in PYTHONCOMPILED is a ':' separated list of\n directories. On Windows, a ';' separated list is used. \n \"\"\"\n paths = []\n if os.environ.has_key('PYTHONCOMPILED'):\n path_string = os.environ['PYTHONCOMPILED'] \n if sys.platform == 'win32':\n #probably should also look in registry\n paths = path_string.split(';')\n else: \n paths = path_string.split(':')\n return paths \n\n def build_search_order(self):\n \"\"\" Returns a list of paths that are searched for catalogs. \n \n Values specified in the catalog constructor are searched first,\n then values found in the PYTHONCOMPILED environment variable.\n The directory returned by default_dir() is always returned at\n the end of the list.\n \n There is a 'magic' path name called 'MODULE' that is replaced\n by the directory defined by set_module_directory(). If the\n module directory hasn't been set, 'MODULE' is ignored.\n \"\"\"\n \n paths = self.user_path_list + self.get_environ_path()\n search_order = []\n for path in paths:\n if path == 'MODULE':\n if self.module_dir:\n search_order.append(self.module_dir)\n else:\n search_order.append(path)\n search_order.append(default_dir())\n return search_order\n\n def get_catalog_files(self):\n \"\"\" Returns catalog file list in correct search order.\n \n Some of the catalog files may not currently exists.\n However, all will be valid locations for a catalog\n to be created (if you have write permission).\n \"\"\"\n files = map(catalog_path,self.build_search_order())\n files = filter(lambda x: x is not None,files)\n return files\n\n def get_existing_files(self):\n \"\"\" Returns all existing catalog file list in correct search order.\n \"\"\"\n files = self.get_catalog_files()\n # open every stinking file to check if it exists.\n # This is because anydbm doesn't provide a consistent naming \n # convention across platforms for its files \n existing_files = []\n for file in files:\n if get_catalog(os.path.dirname(file),'r') is not None:\n existing_files.append(file)\n # This is the non-portable (and much faster) old code\n #existing_files = filter(os.path.exists,files)\n return existing_files\n\n def get_writable_file(self,existing_only=0):\n \"\"\" Return the name of the first writable catalog file.\n \n Its parent directory must also be writable. This is so that\n compiled modules can be written to the same directory.\n \"\"\"\n # note: both file and its parent directory must be writeable\n if existing_only:\n files = self.get_existing_files()\n else:\n files = self.get_catalog_files()\n # filter for (file exists and is writable) OR directory is writable\n def file_test(x):\n from os import access, F_OK, W_OK\n return (access(x,F_OK) and access(x,W_OK) or\n access(os.path.dirname(x),W_OK))\n writable = filter(file_test,files)\n if writable:\n file = writable[0]\n else:\n file = None\n return file\n \n def get_writable_dir(self):\n \"\"\" Return the parent directory of first writable catalog file.\n \n The returned directory has write access.\n \"\"\"\n return os.path.dirname(self.get_writable_file())\n \n def unique_module_name(self,code,module_dir=None):\n \"\"\" Return full path to unique file name that in writable location.\n \n The directory for the file is the first writable directory in \n the catalog search path. The unique file name is derived from\n the code fragment. If, module_dir is specified, it is used\n to replace 'MODULE' in the search path.\n \"\"\"\n if module_dir is not None:\n self.set_module_directory(module_dir)\n try:\n d = self.get_writable_dir()\n finally:\n if module_dir is not None:\n self.clear_module_directory()\n return unique_file(d,code)\n\n def path_key(self,code):\n \"\"\" Return key for path information for functions associated with code.\n \"\"\"\n return '__path__' + code\n \n def configure_path(self,cat,code):\n \"\"\" Add the python path for the given code to the sys.path\n \n unconfigure_path() should be called as soon as possible after\n imports associated with code are finished so that sys.path \n is restored to normal.\n \"\"\"\n try:\n paths = cat[self.path_key(code)]\n self.paths_added = len(paths)\n sys.path = paths + sys.path\n except:\n self.paths_added = 0 \n \n def unconfigure_path(self):\n \"\"\" Restores sys.path to normal after calls to configure_path()\n \n Remove the previously added paths from sys.path\n \"\"\"\n sys.path = sys.path[self.paths_added:]\n self.paths_added = 0\n\n def get_cataloged_functions(self,code):\n \"\"\" Load all functions associated with code from catalog search path.\n \n Sometimes there can be trouble loading a function listed in a\n catalog file because the actual module that holds the function \n has been moved or deleted. When this happens, that catalog file\n is \"repaired\", meaning the entire entry for this function is \n removed from the file. This only affects the catalog file that\n has problems -- not the others in the search path.\n \n The \"repair\" behavior may not be needed, but I'll keep it for now.\n \"\"\"\n mode = 'r'\n cat = None\n function_list = []\n for path in self.build_search_order():\n cat = get_catalog(path,mode)\n if cat is not None and cat.has_key(code):\n # set up the python path so that modules for this\n # function can be loaded.\n self.configure_path(cat,code)\n try: \n function_list += cat[code]\n except: #SystemError and ImportError so far seen \n # problems loading a function from the catalog. Try to\n # repair the cause.\n cat.close()\n self.repair_catalog(path,code)\n self.unconfigure_path() \n return function_list\n\n\n def repair_catalog(self,catalog_path,code):\n \"\"\" Remove entry for code from catalog_path\n \n Occasionally catalog entries could get corrupted. An example\n would be when a module that had functions in the catalog was\n deleted or moved on the disk. The best current repair method is \n just to trash the entire catalog entry for this piece of code. \n This may loose function entries that are valid, but thats life.\n \n catalog_path must be writable for repair. If it isn't, the\n function exists with a warning. \n \"\"\"\n writable_cat = None\n if not os.path.exists(catalog_path):\n return\n try:\n writable_cat = get_catalog(catalog_path,'w')\n except:\n print 'warning: unable to repair catalog entry\\n %s\\n in\\n %s' % \\\n (code,catalog_path)\n return \n if writable_cat.has_key(code):\n print 'repairing catalog by removing key'\n del writable_cat[code]\n \n # it is possible that the path key doesn't exist (if the function registered\n # was a built-in function), so we have to check if the path exists before\n # arbitrarily deleting it.\n path_key = self.path_key(code) \n if writable_cat.has_key(path_key):\n del writable_cat[path_key] \n \n def get_functions_fast(self,code):\n \"\"\" Return list of functions for code from the cache.\n \n Return an empty list if the code entry is not found.\n \"\"\"\n return self.cache.get(code,[])\n \n def get_functions(self,code,module_dir=None):\n \"\"\" Return the list of functions associated with this code fragment.\n \n The cache is first searched for the function. If an entry\n in the cache is not found, then catalog files on disk are \n searched for the entry. This is slooooow, but only happens\n once per code object. All the functions found in catalog files\n on a cache miss are loaded into the cache to speed up future calls.\n The search order is as follows:\n \n 1. user specified path (from catalog initialization)\n 2. directories from the PYTHONCOMPILED environment variable\n 3. The temporary directory on your platform.\n\n The path specified by module_dir will replace the 'MODULE' \n place holder in the catalog search path. See build_search_order()\n for more info on the search path. \n \"\"\" \n # Fast!! try cache first.\n if self.cache.has_key(code):\n return self.cache[code]\n \n # 2. Slow!! read previously compiled functions from disk.\n try:\n self.set_module_directory(module_dir)\n function_list = self.get_cataloged_functions(code)\n # put function_list in cache to save future lookups.\n if function_list:\n self.cache[code] = function_list\n # return function_list, empty or otherwise.\n finally:\n self.clear_module_directory()\n return function_list\n\n def add_function(self,code,function,module_dir=None):\n \"\"\" Adds a function to the catalog.\n \n The function is added to the cache as well as the first\n writable file catalog found in the search path. If no\n code entry exists in the cache, the on disk catalogs\n are loaded into the cache and function is added to the\n beginning of the function list.\n \n The path specified by module_dir will replace the 'MODULE' \n place holder in the catalog search path. See build_search_order()\n for more info on the search path. \n \"\"\" \n\n # 1. put it in the cache.\n if self.cache.has_key(code):\n if function not in self.cache[code]:\n self.cache[code].insert(0,function)\n else:\n # if it is in the cache, then it is also\n # been persisted \n return\n else: \n # Load functions and put this one up front\n self.cache[code] = self.get_functions(code) \n self.fast_cache(code,function)\n # 2. Store the function entry to disk. \n try:\n self.set_module_directory(module_dir)\n self.add_function_persistent(code,function)\n finally:\n self.clear_module_directory()\n \n def add_function_persistent(self,code,function):\n \"\"\" Store the code->function relationship to disk.\n \n Two pieces of information are needed for loading functions\n from disk -- the function pickle (which conveniently stores\n the module name, etc.) and the path to its module's directory.\n The latter is needed so that the function can be loaded no\n matter what the user's Python path is.\n \"\"\" \n # add function to data in first writable catalog\n mode = 'c' # create if doesn't exist, otherwise, use existing\n cat_dir = self.get_writable_dir()\n cat = get_catalog(cat_dir,mode)\n if cat is None:\n cat_dir = default_dir()\n cat = get_catalog(cat_dir,mode)\n if cat is None:\n cat_dir = default_dir() \n cat_file = catalog_path(cat_dir)\n print 'problems with default catalog -- removing'\n import glob\n files = glob.glob(cat_file+'*')\n for f in files:\n os.remove(f)\n cat = get_catalog(cat_dir,mode)\n if cat is None:\n raise ValueError, 'Failed to access a catalog for storing functions' \n # Prabhu was getting some corrupt catalog errors. I'll put a try/except\n # to protect against this, but should really try and track down the issue.\n function_list = [function]\n try:\n function_list = function_list + cat.get(code,[])\n except pickle.UnpicklingError:\n pass\n cat[code] = function_list\n # now add needed path information for loading function\n module = getmodule(function)\n try:\n # built in modules don't have the __file__ extension, so this\n # will fail. Just pass in this case since path additions aren't\n # needed for built-in modules.\n mod_path,f=os.path.split(os.path.abspath(module.__file__))\n pkey = self.path_key(code)\n cat[pkey] = [mod_path] + cat.get(pkey,[])\n except:\n pass\n\n def fast_cache(self,code,function):\n \"\"\" Move function to the front of the cache entry for code\n \n If future calls to the function have the same type signature,\n this will speed up access significantly because the first\n function call is correct.\n \n Note: The cache added to the inline_tools module is significantly\n faster than always calling get_functions, so this isn't\n as necessary as it used to be. Still, it's probably worth\n doing. \n \"\"\"\n try:\n if self.cache[code][0] == function:\n return\n except: # KeyError, IndexError \n pass\n try:\n self.cache[code].remove(function)\n except ValueError:\n pass\n # put new function at the beginning of the list to search.\n self.cache[code].insert(0,function)\n \ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "methods": [ { "name": "getmodule", "long_name": "getmodule( object )", "filename": "catalog.py", "nloc": 13, "complexity": 7, "token_count": 79, "parameters": [ "object" ], "start_line": 52, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 26, "top_nesting_level": 0 }, { "name": "expr_to_filename", "long_name": "expr_to_filename( expr )", "filename": "catalog.py", "nloc": 4, "complexity": 1, "token_count": 24, "parameters": [ "expr" ], "start_line": 79, "end_line": 88, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 0 }, { "name": "unique_file", "long_name": "unique_file( d , expr )", "filename": "catalog.py", "nloc": 13, "complexity": 8, "token_count": 89, "parameters": [ "d", "expr" ], "start_line": 90, "end_line": 112, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 0 }, { "name": "default_dir", "long_name": "default_dir( )", "filename": "catalog.py", "nloc": 18, "complexity": 5, "token_count": 145, "parameters": [], "start_line": 114, "end_line": 147, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 34, "top_nesting_level": 0 }, { "name": "intermediate_dir", "long_name": "intermediate_dir( )", "filename": "catalog.py", "nloc": 7, "complexity": 2, "token_count": 56, "parameters": [], "start_line": 149, "end_line": 158, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 0 }, { "name": "default_temp_dir", "long_name": "default_temp_dir( )", "filename": "catalog.py", "nloc": 9, "complexity": 3, "token_count": 64, "parameters": [], "start_line": 160, "end_line": 168, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 0 }, { "name": "os_dependent_catalog_name", "long_name": "os_dependent_catalog_name( )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 171, "end_line": 183, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 0 }, { "name": "catalog_path", "long_name": "catalog_path( module_path )", "filename": "catalog.py", "nloc": 12, "complexity": 3, "token_count": 105, "parameters": [ "module_path" ], "start_line": 185, "end_line": 210, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 26, "top_nesting_level": 0 }, { "name": "get_catalog", "long_name": "get_catalog( module_path , mode = 'r' )", "filename": "catalog.py", "nloc": 13, "complexity": 6, "token_count": 80, "parameters": [ "module_path", "mode" ], "start_line": 212, "end_line": 239, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 28, "top_nesting_level": 0 }, { "name": "__init__", "long_name": "__init__( self , user_path_list = None )", "filename": "catalog.py", "nloc": 10, "complexity": 3, "token_count": 60, "parameters": [ "self", "user_path_list" ], "start_line": 268, "end_line": 283, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 16, "top_nesting_level": 1 }, { "name": "set_module_directory", "long_name": "set_module_directory( self , module_dir )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self", "module_dir" ], "start_line": 285, "end_line": 291, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "get_module_directory", "long_name": "get_module_directory( self )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 10, "parameters": [ "self" ], "start_line": 292, "end_line": 295, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "clear_module_directory", "long_name": "clear_module_directory( self )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 296, "end_line": 299, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "get_environ_path", "long_name": "get_environ_path( self )", "filename": "catalog.py", "nloc": 9, "complexity": 3, "token_count": 55, "parameters": [ "self" ], "start_line": 301, "end_line": 315, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "build_search_order", "long_name": "build_search_order( self )", "filename": "catalog.py", "nloc": 11, "complexity": 4, "token_count": 62, "parameters": [ "self" ], "start_line": 317, "end_line": 339, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "get_catalog_files", "long_name": "get_catalog_files( self )", "filename": "catalog.py", "nloc": 4, "complexity": 1, "token_count": 34, "parameters": [ "self" ], "start_line": 341, "end_line": 350, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "get_existing_files", "long_name": "get_existing_files( self )", "filename": "catalog.py", "nloc": 7, "complexity": 3, "token_count": 48, "parameters": [ "self" ], "start_line": 352, "end_line": 365, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 14, "top_nesting_level": 1 }, { "name": "get_writable_file.file_test", "long_name": "get_writable_file.file_test( x )", "filename": "catalog.py", "nloc": 4, "complexity": 3, "token_count": 43, "parameters": [ "x" ], "start_line": 379, "end_line": 382, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 2 }, { "name": "get_writable_file", "long_name": "get_writable_file( self , existing_only = 0 )", "filename": "catalog.py", "nloc": 12, "complexity": 3, "token_count": 55, "parameters": [ "self", "existing_only" ], "start_line": 367, "end_line": 388, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "get_writable_dir", "long_name": "get_writable_dir( self )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 390, "end_line": 395, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "unique_module_name", "long_name": "unique_module_name( self , code , module_dir = None )", "filename": "catalog.py", "nloc": 9, "complexity": 4, "token_count": 53, "parameters": [ "self", "code", "module_dir" ], "start_line": 397, "end_line": 412, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 16, "top_nesting_level": 1 }, { "name": "path_key", "long_name": "path_key( self , code )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "self", "code" ], "start_line": 414, "end_line": 417, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "configure_path", "long_name": "configure_path( self , cat , code )", "filename": "catalog.py", "nloc": 7, "complexity": 2, "token_count": 47, "parameters": [ "self", "cat", "code" ], "start_line": 419, "end_line": 431, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "unconfigure_path", "long_name": "unconfigure_path( self )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 24, "parameters": [ "self" ], "start_line": 433, "end_line": 439, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "get_cataloged_functions", "long_name": "get_cataloged_functions( self , code )", "filename": "catalog.py", "nloc": 15, "complexity": 5, "token_count": 86, "parameters": [ "self", "code" ], "start_line": 441, "end_line": 470, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "repair_catalog", "long_name": "repair_catalog( self , catalog_path , code )", "filename": "catalog.py", "nloc": 16, "complexity": 5, "token_count": 83, "parameters": [ "self", "catalog_path", "code" ], "start_line": 473, "end_line": 503, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "get_functions_fast", "long_name": "get_functions_fast( self , code )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 20, "parameters": [ "self", "code" ], "start_line": 505, "end_line": 510, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "get_functions", "long_name": "get_functions( self , code , module_dir = None )", "filename": "catalog.py", "nloc": 11, "complexity": 4, "token_count": 65, "parameters": [ "self", "code", "module_dir" ], "start_line": 512, "end_line": 544, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 33, "top_nesting_level": 1 }, { "name": "add_function", "long_name": "add_function( self , code , function , module_dir = None )", "filename": "catalog.py", "nloc": 14, "complexity": 4, "token_count": 97, "parameters": [ "self", "code", "function", "module_dir" ], "start_line": 546, "end_line": 577, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 32, "top_nesting_level": 1 }, { "name": "add_function_persistent", "long_name": "add_function_persistent( self , code , function )", "filename": "catalog.py", "nloc": 31, "complexity": 7, "token_count": 194, "parameters": [ "self", "code", "function" ], "start_line": 579, "end_line": 624, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 46, "top_nesting_level": 1 }, { "name": "fast_cache", "long_name": "fast_cache( self , code , function )", "filename": "catalog.py", "nloc": 11, "complexity": 4, "token_count": 59, "parameters": [ "self", "code", "function" ], "start_line": 626, "end_line": 648, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 650, "end_line": 652, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 654, "end_line": 656, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "getmodule", "long_name": "getmodule( object )", "filename": "catalog.py", "nloc": 13, "complexity": 7, "token_count": 79, "parameters": [ "object" ], "start_line": 52, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 26, "top_nesting_level": 0 }, { "name": "expr_to_filename", "long_name": "expr_to_filename( expr )", "filename": "catalog.py", "nloc": 4, "complexity": 1, "token_count": 24, "parameters": [ "expr" ], "start_line": 79, "end_line": 88, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 0 }, { "name": "unique_file", "long_name": "unique_file( d , expr )", "filename": "catalog.py", "nloc": 13, "complexity": 8, "token_count": 89, "parameters": [ "d", "expr" ], "start_line": 90, "end_line": 112, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 0 }, { "name": "default_dir", "long_name": "default_dir( )", "filename": "catalog.py", "nloc": 18, "complexity": 5, "token_count": 145, "parameters": [], "start_line": 114, "end_line": 147, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 34, "top_nesting_level": 0 }, { "name": "intermediate_dir", "long_name": "intermediate_dir( )", "filename": "catalog.py", "nloc": 7, "complexity": 2, "token_count": 56, "parameters": [], "start_line": 149, "end_line": 158, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 0 }, { "name": "default_temp_dir", "long_name": "default_temp_dir( )", "filename": "catalog.py", "nloc": 9, "complexity": 3, "token_count": 64, "parameters": [], "start_line": 160, "end_line": 168, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 0 }, { "name": "os_dependent_catalog_name", "long_name": "os_dependent_catalog_name( )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 171, "end_line": 183, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 0 }, { "name": "catalog_path", "long_name": "catalog_path( module_path )", "filename": "catalog.py", "nloc": 12, "complexity": 3, "token_count": 105, "parameters": [ "module_path" ], "start_line": 185, "end_line": 210, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 26, "top_nesting_level": 0 }, { "name": "get_catalog", "long_name": "get_catalog( module_path , mode = 'r' )", "filename": "catalog.py", "nloc": 13, "complexity": 6, "token_count": 80, "parameters": [ "module_path", "mode" ], "start_line": 212, "end_line": 239, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 28, "top_nesting_level": 0 }, { "name": "__init__", "long_name": "__init__( self , user_path_list = None )", "filename": "catalog.py", "nloc": 10, "complexity": 3, "token_count": 60, "parameters": [ "self", "user_path_list" ], "start_line": 268, "end_line": 283, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 16, "top_nesting_level": 1 }, { "name": "set_module_directory", "long_name": "set_module_directory( self , module_dir )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self", "module_dir" ], "start_line": 285, "end_line": 291, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "get_module_directory", "long_name": "get_module_directory( self )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 10, "parameters": [ "self" ], "start_line": 292, "end_line": 295, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "clear_module_directory", "long_name": "clear_module_directory( self )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 296, "end_line": 299, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "get_environ_path", "long_name": "get_environ_path( self )", "filename": "catalog.py", "nloc": 9, "complexity": 3, "token_count": 55, "parameters": [ "self" ], "start_line": 301, "end_line": 315, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "build_search_order", "long_name": "build_search_order( self )", "filename": "catalog.py", "nloc": 11, "complexity": 4, "token_count": 62, "parameters": [ "self" ], "start_line": 317, "end_line": 339, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "get_catalog_files", "long_name": "get_catalog_files( self )", "filename": "catalog.py", "nloc": 4, "complexity": 1, "token_count": 34, "parameters": [ "self" ], "start_line": 341, "end_line": 350, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "get_existing_files", "long_name": "get_existing_files( self )", "filename": "catalog.py", "nloc": 7, "complexity": 3, "token_count": 48, "parameters": [ "self" ], "start_line": 352, "end_line": 365, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 14, "top_nesting_level": 1 }, { "name": "get_writable_file.file_test", "long_name": "get_writable_file.file_test( x )", "filename": "catalog.py", "nloc": 4, "complexity": 3, "token_count": 43, "parameters": [ "x" ], "start_line": 379, "end_line": 382, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 2 }, { "name": "get_writable_file", "long_name": "get_writable_file( self , existing_only = 0 )", "filename": "catalog.py", "nloc": 12, "complexity": 3, "token_count": 55, "parameters": [ "self", "existing_only" ], "start_line": 367, "end_line": 388, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "get_writable_dir", "long_name": "get_writable_dir( self )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 390, "end_line": 395, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "unique_module_name", "long_name": "unique_module_name( self , code , module_dir = None )", "filename": "catalog.py", "nloc": 9, "complexity": 4, "token_count": 53, "parameters": [ "self", "code", "module_dir" ], "start_line": 397, "end_line": 412, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 16, "top_nesting_level": 1 }, { "name": "path_key", "long_name": "path_key( self , code )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "self", "code" ], "start_line": 414, "end_line": 417, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "configure_path", "long_name": "configure_path( self , cat , code )", "filename": "catalog.py", "nloc": 7, "complexity": 2, "token_count": 47, "parameters": [ "self", "cat", "code" ], "start_line": 419, "end_line": 431, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "unconfigure_path", "long_name": "unconfigure_path( self )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 24, "parameters": [ "self" ], "start_line": 433, "end_line": 439, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "get_cataloged_functions", "long_name": "get_cataloged_functions( self , code )", "filename": "catalog.py", "nloc": 15, "complexity": 5, "token_count": 86, "parameters": [ "self", "code" ], "start_line": 441, "end_line": 470, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "repair_catalog", "long_name": "repair_catalog( self , catalog_path , code )", "filename": "catalog.py", "nloc": 16, "complexity": 5, "token_count": 83, "parameters": [ "self", "catalog_path", "code" ], "start_line": 473, "end_line": 503, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "get_functions_fast", "long_name": "get_functions_fast( self , code )", "filename": "catalog.py", "nloc": 2, "complexity": 1, "token_count": 20, "parameters": [ "self", "code" ], "start_line": 505, "end_line": 510, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "get_functions", "long_name": "get_functions( self , code , module_dir = None )", "filename": "catalog.py", "nloc": 11, "complexity": 4, "token_count": 65, "parameters": [ "self", "code", "module_dir" ], "start_line": 512, "end_line": 544, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 33, "top_nesting_level": 1 }, { "name": "add_function", "long_name": "add_function( self , code , function , module_dir = None )", "filename": "catalog.py", "nloc": 14, "complexity": 4, "token_count": 97, "parameters": [ "self", "code", "function", "module_dir" ], "start_line": 546, "end_line": 577, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 32, "top_nesting_level": 1 }, { "name": "add_function_persistent", "long_name": "add_function_persistent( self , code , function )", "filename": "catalog.py", "nloc": 31, "complexity": 7, "token_count": 194, "parameters": [ "self", "code", "function" ], "start_line": 579, "end_line": 624, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 46, "top_nesting_level": 1 }, { "name": "fast_cache", "long_name": "fast_cache( self , code , function )", "filename": "catalog.py", "nloc": 11, "complexity": 4, "token_count": 59, "parameters": [ "self", "code", "function" ], "start_line": 626, "end_line": 648, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 650, "end_line": 652, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "catalog.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 654, "end_line": 656, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [], "nloc": 351, "complexity": 100, "token_count": 1908, "diff_parsed": { "added": [ " dumb = 1" ], "deleted": [ " dumb == 1" ] } } ] }, { "hash": "5472eedf02fd8647ad3dfc246c1a65388ceb907a", "msg": "added a couple of implementations using lists instead of Numeric arrays. They are very slow.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-15T21:39:59+00:00", "author_timezone": 0, "committer_date": "2002-01-15T21:39:59+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "68b8d1007e6b92f3fb4c218196a384c86039598d" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 7, "insertions": 73, "lines": 80, "files": 1, "dmm_unit_size": 0.55, "dmm_unit_complexity": 0.0, "dmm_unit_interfacing": 0.45, "modified_files": [ { "old_path": "weave/examples/ramp.py", "new_path": "weave/examples/ramp.py", "filename": "ramp.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -1,3 +1,20 @@\n+\"\"\" Comparison of several different ways of calculating a \"ramp\"\n+ function.\n+ \n+ C:\\home\\ej\\wrk\\junk\\scipy\\weave\\examples>python ramp.py \n+ python (seconds*ratio): 128.149998188\n+ arr[500]: 0.0500050005001\n+ compiled numeric1 (seconds, speed up): 1.42199993134 90.1195530071\n+ arr[500]: 0.0500050005001\n+ compiled numeric2 (seconds, speed up): 0.950999975204 134.752893301\n+ arr[500]: 0.0500050005001\n+ compiled list1 (seconds, speed up): 53.100001812 2.41337088164\n+ arr[500]: 0.0500050005001\n+ compiled list4 (seconds, speed up): 30.5500030518 4.19476220578\n+ arr[500]: 0.0500050005001 \n+\n+\"\"\"\n+\n import time\n import weave\n from Numeric import *\n@@ -27,6 +44,30 @@ def Ramp_numeric2(result,size,start,end):\n }\n \"\"\"\n weave.inline(code,['result','size','start','end'],compiler='gcc')\n+\n+def Ramp_list1(result, size, start, end):\n+ code = \"\"\"\n+ double step = (end-start)/(size-1);\n+ int i; \n+ for (i = 0; i < size; i++) \n+ {\n+ result[i] = Py::Float(start + step*i);\n+ }\n+ \"\"\"\n+ weave.inline(code, [\"result\", \"size\", \"start\", \"end\"], verbose=2)\n+\n+def Ramp_list2(result, size, start, end):\n+ code = \"\"\"\n+ double step = (end-start)/(size-1);\n+ int i;\n+ PyObject* raw_result = result.ptr();\n+ for (i = 0; i < size; i++) \n+ {\n+ PyObject* val = PyFloat_FromDouble( start + step*i );\n+ PySequence_SetItem(raw_result,i, val);\n+ }\n+ \"\"\"\n+ weave.inline(code, [\"result\", \"size\", \"start\", \"end\"], verbose=2)\n \n def main():\n N_array = 10000\n@@ -44,29 +85,54 @@ def main():\n print 'python (seconds*ratio):', py_time\n print 'arr[500]:', arr[500]\n \n- arr = array([0]*N_array,Float64)\n+ arr1 = array([0]*N_array,Float64)\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n- Ramp_numeric1(arr, N_array, 0.0, 1.0)\n+ Ramp_numeric1(arr1, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_c):\n- Ramp_numeric1(arr, N_array, 0.0, 1.0)\n+ Ramp_numeric1(arr1, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1)\n print 'compiled numeric1 (seconds, speed up):', c_time, py_time/ c_time\n- print 'arr[500]:', arr[500]\n+ print 'arr[500]:', arr1[500]\n \n arr2 = array([0]*N_array,Float64)\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n- Ramp_numeric2(arr, N_array, 0.0, 1.0)\n+ Ramp_numeric2(arr2, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_c):\n- Ramp_numeric2(arr, N_array, 0.0, 1.0)\n+ Ramp_numeric2(arr2, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1) \n print 'compiled numeric2 (seconds, speed up):', c_time, py_time/ c_time\n- print 'arr[500]:', arr[500]\n+ print 'arr[500]:', arr2[500]\n+\n+ arr3 = [0]*N_array\n+ # First call compiles function or loads from cache.\n+ # I'm not including this in the timing.\n+ Ramp_list1(arr3, N_array, 0.0, 1.0)\n+ t1 = time.time()\n+ for i in xrange(N_py):\n+ Ramp_list1(arr3, N_array, 0.0, 1.0)\n+ t2 = time.time()\n+ c_time = (t2 - t1) * ratio \n+ print 'compiled list1 (seconds, speed up):', c_time, py_time/ c_time\n+ print 'arr[500]:', arr3[500]\n+ \n+ arr4 = [0]*N_array\n+ # First call compiles function or loads from cache.\n+ # I'm not including this in the timing.\n+ Ramp_list2(arr4, N_array, 0.0, 1.0)\n+ t1 = time.time()\n+ for i in xrange(N_py):\n+ Ramp_list2(arr4, N_array, 0.0, 1.0)\n+ t2 = time.time()\n+ c_time = (t2 - t1) * ratio \n+ print 'compiled list4 (seconds, speed up):', c_time, py_time/ c_time\n+ print 'arr[500]:', arr4[500]\n+ \n \n if __name__ == '__main__':\n main()\n\\ No newline at end of file\n", "added_lines": 73, "deleted_lines": 7, "source_code": "\"\"\" Comparison of several different ways of calculating a \"ramp\"\n function.\n \n C:\\home\\ej\\wrk\\junk\\scipy\\weave\\examples>python ramp.py \n python (seconds*ratio): 128.149998188\n arr[500]: 0.0500050005001\n compiled numeric1 (seconds, speed up): 1.42199993134 90.1195530071\n arr[500]: 0.0500050005001\n compiled numeric2 (seconds, speed up): 0.950999975204 134.752893301\n arr[500]: 0.0500050005001\n compiled list1 (seconds, speed up): 53.100001812 2.41337088164\n arr[500]: 0.0500050005001\n compiled list4 (seconds, speed up): 30.5500030518 4.19476220578\n arr[500]: 0.0500050005001 \n\n\"\"\"\n\nimport time\nimport weave\nfrom Numeric import *\n\ndef Ramp(result, size, start, end):\n step = (end-start)/(size-1)\n for i in xrange(size):\n result[i] = start + step*i\n\ndef Ramp_numeric1(result,size,start,end):\n code = \"\"\"\n double step = (end-start)/(size-1);\n double val = start;\n for (int i = 0; i < size; i++)\n *result_data++ = start + step*i;\n \"\"\"\n weave.inline(code,['result','size','start','end'],compiler='gcc')\n\ndef Ramp_numeric2(result,size,start,end):\n code = \"\"\"\n double step = (end-start)/(size-1);\n double val = start;\n for (int i = 0; i < size; i++)\n {\n result_data[i] = val;\n val += step; \n }\n \"\"\"\n weave.inline(code,['result','size','start','end'],compiler='gcc')\n\ndef Ramp_list1(result, size, start, end):\n code = \"\"\"\n double step = (end-start)/(size-1);\n int i; \n for (i = 0; i < size; i++) \n {\n result[i] = Py::Float(start + step*i);\n }\n \"\"\"\n weave.inline(code, [\"result\", \"size\", \"start\", \"end\"], verbose=2)\n\ndef Ramp_list2(result, size, start, end):\n code = \"\"\"\n double step = (end-start)/(size-1);\n int i;\n PyObject* raw_result = result.ptr();\n for (i = 0; i < size; i++) \n {\n PyObject* val = PyFloat_FromDouble( start + step*i );\n PySequence_SetItem(raw_result,i, val);\n }\n \"\"\"\n weave.inline(code, [\"result\", \"size\", \"start\", \"end\"], verbose=2)\n \ndef main():\n N_array = 10000\n N_py = 200\n N_c = 10000\n \n ratio = float(N_c) / N_py \n \n arr = [0]*N_array\n t1 = time.time()\n for i in xrange(N_py):\n Ramp(arr, N_array, 0.0, 1.0)\n t2 = time.time()\n py_time = (t2 - t1) * ratio\n print 'python (seconds*ratio):', py_time\n print 'arr[500]:', arr[500]\n \n arr1 = array([0]*N_array,Float64)\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n Ramp_numeric1(arr1, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_c):\n Ramp_numeric1(arr1, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1)\n print 'compiled numeric1 (seconds, speed up):', c_time, py_time/ c_time\n print 'arr[500]:', arr1[500]\n\n arr2 = array([0]*N_array,Float64)\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n Ramp_numeric2(arr2, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_c):\n Ramp_numeric2(arr2, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1) \n print 'compiled numeric2 (seconds, speed up):', c_time, py_time/ c_time\n print 'arr[500]:', arr2[500]\n\n arr3 = [0]*N_array\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n Ramp_list1(arr3, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_py):\n Ramp_list1(arr3, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1) * ratio \n print 'compiled list1 (seconds, speed up):', c_time, py_time/ c_time\n print 'arr[500]:', arr3[500]\n \n arr4 = [0]*N_array\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n Ramp_list2(arr4, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_py):\n Ramp_list2(arr4, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1) * ratio \n print 'compiled list4 (seconds, speed up):', c_time, py_time/ c_time\n print 'arr[500]:', arr4[500]\n \n \nif __name__ == '__main__':\n main()", "source_code_before": "import time\nimport weave\nfrom Numeric import *\n\ndef Ramp(result, size, start, end):\n step = (end-start)/(size-1)\n for i in xrange(size):\n result[i] = start + step*i\n\ndef Ramp_numeric1(result,size,start,end):\n code = \"\"\"\n double step = (end-start)/(size-1);\n double val = start;\n for (int i = 0; i < size; i++)\n *result_data++ = start + step*i;\n \"\"\"\n weave.inline(code,['result','size','start','end'],compiler='gcc')\n\ndef Ramp_numeric2(result,size,start,end):\n code = \"\"\"\n double step = (end-start)/(size-1);\n double val = start;\n for (int i = 0; i < size; i++)\n {\n result_data[i] = val;\n val += step; \n }\n \"\"\"\n weave.inline(code,['result','size','start','end'],compiler='gcc')\n \ndef main():\n N_array = 10000\n N_py = 200\n N_c = 10000\n \n ratio = float(N_c) / N_py \n \n arr = [0]*N_array\n t1 = time.time()\n for i in xrange(N_py):\n Ramp(arr, N_array, 0.0, 1.0)\n t2 = time.time()\n py_time = (t2 - t1) * ratio\n print 'python (seconds*ratio):', py_time\n print 'arr[500]:', arr[500]\n \n arr = array([0]*N_array,Float64)\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n Ramp_numeric1(arr, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_c):\n Ramp_numeric1(arr, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1)\n print 'compiled numeric1 (seconds, speed up):', c_time, py_time/ c_time\n print 'arr[500]:', arr[500]\n\n arr2 = array([0]*N_array,Float64)\n # First call compiles function or loads from cache.\n # I'm not including this in the timing.\n Ramp_numeric2(arr, N_array, 0.0, 1.0)\n t1 = time.time()\n for i in xrange(N_c):\n Ramp_numeric2(arr, N_array, 0.0, 1.0)\n t2 = time.time()\n c_time = (t2 - t1) \n print 'compiled numeric2 (seconds, speed up):', c_time, py_time/ c_time\n print 'arr[500]:', arr[500]\n \nif __name__ == '__main__':\n main()", "methods": [ { "name": "Ramp", "long_name": "Ramp( result , size , start , end )", "filename": "ramp.py", "nloc": 4, "complexity": 2, "token_count": 42, "parameters": [ "result", "size", "start", "end" ], "start_line": 22, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 0 }, { "name": "Ramp_numeric1", "long_name": "Ramp_numeric1( result , size , start , end )", "filename": "ramp.py", "nloc": 8, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 0 }, { "name": "Ramp_numeric2", "long_name": "Ramp_numeric2( result , size , start , end )", "filename": "ramp.py", "nloc": 11, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 36, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 }, { "name": "Ramp_list1", "long_name": "Ramp_list1( result , size , start , end )", "filename": "ramp.py", "nloc": 10, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 48, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 0 }, { "name": "Ramp_list2", "long_name": "Ramp_list2( result , size , start , end )", "filename": "ramp.py", "nloc": 12, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 59, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 0 }, { "name": "main", "long_name": "main( )", "filename": "ramp.py", "nloc": 49, "complexity": 6, "token_count": 414, "parameters": [], "start_line": 72, "end_line": 134, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 63, "top_nesting_level": 0 } ], "methods_before": [ { "name": "Ramp", "long_name": "Ramp( result , size , start , end )", "filename": "ramp.py", "nloc": 4, "complexity": 2, "token_count": 42, "parameters": [ "result", "size", "start", "end" ], "start_line": 5, "end_line": 8, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 0 }, { "name": "Ramp_numeric1", "long_name": "Ramp_numeric1( result , size , start , end )", "filename": "ramp.py", "nloc": 8, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 10, "end_line": 17, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 0 }, { "name": "Ramp_numeric2", "long_name": "Ramp_numeric2( result , size , start , end )", "filename": "ramp.py", "nloc": 11, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 19, "end_line": 29, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 }, { "name": "main", "long_name": "main( )", "filename": "ramp.py", "nloc": 31, "complexity": 4, "token_count": 252, "parameters": [], "start_line": 31, "end_line": 69, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "Ramp_list2", "long_name": "Ramp_list2( result , size , start , end )", "filename": "ramp.py", "nloc": 12, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 59, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 0 }, { "name": "main", "long_name": "main( )", "filename": "ramp.py", "nloc": 49, "complexity": 6, "token_count": 414, "parameters": [], "start_line": 72, "end_line": 134, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 63, "top_nesting_level": 0 }, { "name": "Ramp_list1", "long_name": "Ramp_list1( result , size , start , end )", "filename": "ramp.py", "nloc": 10, "complexity": 1, "token_count": 34, "parameters": [ "result", "size", "start", "end" ], "start_line": 48, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 0 } ], "nloc": 115, "complexity": 12, "token_count": 615, "diff_parsed": { "added": [ "\"\"\" Comparison of several different ways of calculating a \"ramp\"", " function.", "", " C:\\home\\ej\\wrk\\junk\\scipy\\weave\\examples>python ramp.py", " python (seconds*ratio): 128.149998188", " arr[500]: 0.0500050005001", " compiled numeric1 (seconds, speed up): 1.42199993134 90.1195530071", " arr[500]: 0.0500050005001", " compiled numeric2 (seconds, speed up): 0.950999975204 134.752893301", " arr[500]: 0.0500050005001", " compiled list1 (seconds, speed up): 53.100001812 2.41337088164", " arr[500]: 0.0500050005001", " compiled list4 (seconds, speed up): 30.5500030518 4.19476220578", " arr[500]: 0.0500050005001", "", "\"\"\"", "", "", "def Ramp_list1(result, size, start, end):", " code = \"\"\"", " double step = (end-start)/(size-1);", " int i;", " for (i = 0; i < size; i++)", " {", " result[i] = Py::Float(start + step*i);", " }", " \"\"\"", " weave.inline(code, [\"result\", \"size\", \"start\", \"end\"], verbose=2)", "", "def Ramp_list2(result, size, start, end):", " code = \"\"\"", " double step = (end-start)/(size-1);", " int i;", " PyObject* raw_result = result.ptr();", " for (i = 0; i < size; i++)", " {", " PyObject* val = PyFloat_FromDouble( start + step*i );", " PySequence_SetItem(raw_result,i, val);", " }", " \"\"\"", " weave.inline(code, [\"result\", \"size\", \"start\", \"end\"], verbose=2)", " arr1 = array([0]*N_array,Float64)", " Ramp_numeric1(arr1, N_array, 0.0, 1.0)", " Ramp_numeric1(arr1, N_array, 0.0, 1.0)", " print 'arr[500]:', arr1[500]", " Ramp_numeric2(arr2, N_array, 0.0, 1.0)", " Ramp_numeric2(arr2, N_array, 0.0, 1.0)", " print 'arr[500]:', arr2[500]", "", " arr3 = [0]*N_array", " # First call compiles function or loads from cache.", " # I'm not including this in the timing.", " Ramp_list1(arr3, N_array, 0.0, 1.0)", " t1 = time.time()", " for i in xrange(N_py):", " Ramp_list1(arr3, N_array, 0.0, 1.0)", " t2 = time.time()", " c_time = (t2 - t1) * ratio", " print 'compiled list1 (seconds, speed up):', c_time, py_time/ c_time", " print 'arr[500]:', arr3[500]", "", " arr4 = [0]*N_array", " # First call compiles function or loads from cache.", " # I'm not including this in the timing.", " Ramp_list2(arr4, N_array, 0.0, 1.0)", " t1 = time.time()", " for i in xrange(N_py):", " Ramp_list2(arr4, N_array, 0.0, 1.0)", " t2 = time.time()", " c_time = (t2 - t1) * ratio", " print 'compiled list4 (seconds, speed up):', c_time, py_time/ c_time", " print 'arr[500]:', arr4[500]", "" ], "deleted": [ " arr = array([0]*N_array,Float64)", " Ramp_numeric1(arr, N_array, 0.0, 1.0)", " Ramp_numeric1(arr, N_array, 0.0, 1.0)", " print 'arr[500]:', arr[500]", " Ramp_numeric2(arr, N_array, 0.0, 1.0)", " Ramp_numeric2(arr, N_array, 0.0, 1.0)", " print 'arr[500]:', arr[500]" ] } } ] }, { "hash": "653df5af033fd2514869639131074f58c68a2f38", "msg": "patched an error in the string printing section -- forgot to convert from Py::String to a char*.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-15T21:51:56+00:00", "author_timezone": 0, "committer_date": "2002-01-15T21:51:56+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "5472eedf02fd8647ad3dfc246c1a65388ceb907a" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 3, "insertions": 11, "lines": 14, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/doc/tutorial.html", "new_path": "weave/doc/tutorial.html", "filename": "tutorial.html", "extension": "html", "change_type": "MODIFY", "diff": "@@ -499,13 +499,21 @@

More with printf

\n
\n \n

\n-For printing strings, the format statement needs to be changed.\n+For printing strings, the format statement needs to be changed. Also, weave\n+doesn't convert strings to char*. Instead it uses CXX Py::String type, so \n+you have to do a little more work. Here we convert it to a C++ std::string\n+and then ask cor the char* version.\n \n

    \n-    >>> a = 'string'\n-    >>> weave.inline(r'printf(\"%s\\n\",a);',['a'])\n+    >>> a = 'string'    \n+    >>> weave.inline(r'printf(\"%s\\n\",std::string(a).c_str());',['a'])\n     string\n     
\n+

\n+ \n+This is a little convoluted. Perhaps strings should convert to std::string\n+objects instead of CXX objects. Or maybe to char*.\n+\n \n

\n As in this case, C/C++ code fragments often have to change to accept different \n", "added_lines": 11, "deleted_lines": 3, "source_code": "\n

Weave Documentation

\n

\nBy Eric Jones eric@enthought.com\n

\n

Outline

\n
\n
Introduction\n
Requirements\n
Installation\n
Testing\n
Benchmarks\n
Inline\n
\n
More with printf\n
\n More examples\n
\n
Binary search\n
Dictionary sort\n
Numeric -- cast/copy/transpose\n
wxPython
\n
\n
Keyword options\n
Returning values\n
\n
\n The issue with locals()
\n
\n
A quick look at the code\n
\n Technical Details\n
\n
Converting Types\n
\n
\n Numeric Argument Conversion\n
\n String, List, Tuple, and Dictionary Conversion\n
File Conversion \n
\n Callable, Instance, and Module Conversion \n
Customizing Conversions\n
\n
Compiling Code\n
\"Cataloging\" functions\n
\n
Function Storage\n
The PYTHONCOMPILED evnironment variable
\n
\n
\n
\n
\n
\n
Blitz\n
\n
Requirements\n
Limitations\n
Numeric Efficiency Issues\n
The Tools \n
\n
Parser\n
Blitz and Numeric\n
\n
Type defintions and coersion\n
Cataloging Compiled Functions\n
Checking Array Sizes\n
Creating the Extension Module\n
\n
Extension Modules\n
\n
A Simple Example\n
Fibonacci Example\n
\n
Customizing Type Conversions -- Type Factories (not written)\n
\n
Type Specifications\n
Type Information\n
The Conversion Process \n
\n
\n\n

Introduction

\n\n

\nThe weave package provides tools for including C/C++ code within\nin Python code. This offers both another level of optimization to those who need \nit, and an easy way to modify and extend any supported extension libraries such \nas wxPython and hopefully VTK soon. Inlining C/C++ code within Python generally\nresults in speed ups of 1.5x to 30x speed-up over algorithms written in pure\nPython (However, it is also possible to slow things down...). Generally \nalgorithms that require a large number of calls to the Python API don't benefit\nas much from the conversion to C/C++ as algorithms that have inner loops \ncompletely convertable to C.\n

\nThere are three basic ways to use weave. The \nweave.inline() function executes C code directly within Python, \nand weave.blitz() translates Python Numeric expressions to C++ \nfor fast execution. blitz() was the original reason \nweave was built. For those interested in building extension\nlibraries, the ext_tools module provides classes for building \nextension modules within Python. \n

\nMost of weave's functionality should work on Windows and Unix, \nalthough some of its functionality requires gcc or a similarly \nmodern C++ compiler that handles templates well. Up to now, most testing has \nbeen done on Windows 2000 with Microsoft's C++ compiler (MSVC) and with gcc \n(mingw32 2.95.2 and 2.95.3-6). All tests also pass on Linux (RH 7.1 \nwith gcc 2.96), and I've had reports that it works on Debian also (thanks \nPearu).\n

\nThe inline and blitz provide new functionality to \nPython (although I've recently learned about the PyInline project which may offer \nsimilar functionality to inline). On the other hand, tools for \nbuilding Python extension modules already exists (SWIG, SIP, pycpp, CXX, and \nothers). As of yet, I'm not sure where weave fits in this \nspectrum. It is closest in flavor to CXX in that it makes creating new C/C++ \nextension modules pretty easy. However, if you're wrapping a gaggle of legacy \nfunctions or classes, SWIG and friends are definitely the better choice. \nweave is set up so that you can customize how Python types are \nconverted to C types in weave. This is great for \ninline(), but, for wrapping legacy code, it is more flexible to \nspecify things the other way around -- that is how C types map to Python types. \nThis weave does not do. I guess it would be possible to build \nsuch a tool on top of weave, but with good tools like SWIG around, \nI'm not sure the effort produces any new capabilities. Things like function \noverloading are probably easily implemented in weave and it might \nbe easier to mix Python/C code in function calls, but nothing beyond this comes \nto mind. So, if you're developing new extension modules or optimizing Python \nfunctions in C, weave.ext_tools() might be the tool \nfor you. If you're wrapping legacy code, stick with SWIG.\n

\nThe next several sections give the basics of how to use weave.\nWe'll discuss what's happening under the covers in more detail later \non. Serious users will need to at least look at the type conversion section to \nunderstand how Python variables map to C/C++ types and how to customize this \nbehavior. One other note. If you don't know C or C++ then these docs are \nprobably of very little help to you. Further, it'd be helpful if you know \nsomething about writing Python extensions. weave does quite a \nbit for you, but for anything complex, you'll need to do some conversions, \nreference counting, etc.\n

\n\nNote: weave is actually part of the SciPy package. However, it works fine as a \nstandalone package. The examples here are given as if it is used as a stand \nalone package. If you are using from within scipy, you can use from \nscipy import weave and the examples will work identically.\n\n\n

Requirements

\n\n

\n\n\n

Installation

\n

\nThere are currently two ways to get weave. Fist, \nweave is part of SciPy and installed automatically (as a sub-\npackage) whenever SciPy is installed (although the latest version isn't in \nSciPy yet, so use this one for now). Second, since weave is \nuseful outside of the scientific community, it has been setup so that it can be\nused as a stand-alone module. \n\n

\nThe stand-alone version can be downloaded from here. Unix users should grab the \ntar ball (.tgz file) and install it using the following commands.\n\n

\n    tar -xzvf weave-0.2.tar.gz\n    cd weave-0.2\n    python setup.py install\n    
\n\nThis will also install two other packages, scipy_distutils and \nscipy_test. The first is needed by the setup process itself and \nboth are used in the unit-testing process. Numeric is required if you want to \nuse blitz(), but isn't necessary for inline() or \next_tools\n

\nFor Windows users, it's even easier. You can download the click-install .exe \nfile and run it for automatic installation. There is also a .zip file of the\nsource for those interested. It also includes a setup.py file to simplify\ninstallation. \n

\nIf you're using the CVS version, you'll need to install \nscipy_distutils and scipy_test packages (also \navailable from CVS) on your own.\n

\n \nNote: The dependency issue here is a little sticky. I hate to make people \ndownload more than one file (and so I haven't), but distutils doesn't have a \nway to do conditional installation -- at least that I know about. This can \nlead to undesired clobbering of the scipy_test and scipy_distutils modules. \nWhat to do, what to do... Right now it is a very minor issue.\n\n

\n\n

Testing

\nOnce weave is installed, fire up python and run its unit tests.\n\n
\n    >>> import weave\n    >>> weave.test()\n    runs long time... spews tons of output and a few warnings\n    .\n    .\n    .\n    ..............................................................\n    ................................................................\n    ..................................................\n    ----------------------------------------------------------------------\n    Ran 184 tests in 158.418s\n\n    OK\n    \n    >>> \n    
\n\nThis takes a loooong time. On windows, it is usually several minutes. On Unix \nwith remote file systems, I've had it take 15 or so minutes. In the end, it \nshould run about 180 tests and spew some speed results along the way. If you \nget errors, they'll be reported at the end of the output. Please let me know\nwhat if this occurs.\n\nIf you don't have Numeric installed, you'll get some module import errors \nduring the test setup phase for modules that are Numeric specific (blitz_spec, \nblitz_tools, size_check, standard_array_spec, ast_tools), but all test should\npass (about 100 and they should complete in several minutes).\n

\nIf you only want to test a single module of the package, you can do this by\nrunning test() for that specific module.\n\n

\n    >>> import weave.scalar_spec\n    >>> weave.scalar_spec.test()\n    .......\n    ----------------------------------------------------------------------\n    Ran 7 tests in 23.284s\n    
\n\nTesting Notes:\n\n\n\n

Benchmarks

\nThis section has a few benchmarks -- thats all people want to see anyway right? \nThese are mostly taken from running files in the weave/example \ndirectory and also from the test scripts. Without more information about what \nthe test actually do, their value is limited. Still, their here for the \ncurious. Look at the example scripts for more specifics about what problem was \nactually solved by each run. These examples are run under windows 2000 using \nMicrosoft Visual C++ and python2.1 on a 850 MHz PIII laptop with 320 MB of RAM.\nSpeed up is the improvement (degredation) factor of weave compared to \nconventional Python functions. The blitz() comparisons are shown\ncompared to Numeric.\n

\n

\n\n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n
\n

inline and ext_tools

Algorithm

Speed up

binary search   1.50
fibonacci (recursive)  82.10
fibonacci (loop)   9.17
return None   0.14
map   1.20
dictionary sort   2.54
vector quantization  37.40
\n

blitz -- double precision

Algorithm

Speed up

a = b + c 512x512   3.05
a = b + c + d 512x512   4.59
5 pt avg. filter, 2D Image 512x512   9.01
Electromagnetics (FDTD) 100x100x100   8.61
\n
\n

\n\nThe benchmarks shown blitz in the best possible light. Numeric \n(at least on my machine) is significantly worse for double precision than it is \nfor single precision calculations. If your interested in single precision \nresults, you can pretty much divide the double precision speed up by 3 and you'll\nbe close.\n\n\n

Inline

\n

\ninline() compiles and executes C/C++ code on the fly. Variables \nin the local and global Python scope are also available in the C/C++ code. \nValues are passed to the C/C++ code by assignment much like variables \nare passed into a standard Python function. Values are returned from the C/C++ \ncode through a special argument called return_val. Also, the contents of \nmutable objects can be changed within the C/C++ code and the changes remain \nafter the C code exits and returns to Python. (more on this later)\n

\nHere's a trivial printf example using inline():\n\n

\n    >>> import weave    \n    >>> a  = 1\n    >>> weave.inline('printf(\"%d\\\\n\",a);',['a'])\n    1\n    
\n

\nIn this, its most basic form, inline(c_code, var_list) requires two \narguments. c_code is a string of valid C/C++ code. \nvar_list is a list of variable names that are passed from \nPython into C/C++. Here we have a simple printf statement that \nwrites the Python variable a to the screen. The first time you run \nthis, there will be a pause while the code is written to a .cpp file, compiled \ninto an extension module, loaded into Python, cataloged for future use, and \nexecuted. On windows (850 MHz PIII), this takes about 1.5 seconds when using \nMicrosoft's C++ compiler (MSVC) and 6-12 seconds using gcc (mingw32 2.95.2). \nAll subsequent executions of the code will happen very quickly because the code \nonly needs to be compiled once. If you kill and restart the interpreter and then \nexecute the same code fragment again, there will be a much shorter delay in the \nfractions of seconds range. This is because weave stores a \ncatalog of all previously compiled functions in an on disk cache. When it sees \na string that has been compiled, it loads the already compiled module and \nexecutes the appropriate function. \n

\n\nNote: If you try the printf example in a GUI shell such as IDLE, \nPythonWin, PyShell, etc., you're unlikely to see the output. This is because the \nC code is writing to stdout, instead of to the GUI window. This doesn't mean \nthat inline doesn't work in these environments -- it only means that standard \nout in C is not the same as the standard out for Python in these cases. Non \ninput/output functions will work as expected.\n\n

\nAlthough effort has been made to reduce the overhead associated with calling \ninline, it is still less efficient for simple code snippets than using \nequivalent Python code. The simple printf example is actually \nslower by 30% or so than using Python print statement. And, it is \nnot difficult to create code fragments that are 8-10 times slower using inline \nthan equivalent Python. However, for more complicated algorithms, \nthe speed up can be worth while -- anywhwere from 1.5- 30 times faster. \nAlgorithms that have to manipulate Python objects (sorting a list) usually only \nsee a factor of 2 or so improvement. Algorithms that are highly computational \nor manipulate Numeric arrays can see much larger improvements. The \nexamples/vq.py file shows a factor of 30 or more improvement on the vector \nquantization algorithm that is used heavily in information theory and \nclassification problems.\n

\n\n\n

More with printf

\n

\nMSVC users will actually see a bit of compiler output that distutils does not\nsupress the first time the code executes:\n\n

    \n    >>> weave.inline(r'printf(\"%d\\n\",a);',['a'])\n    sc_e013937dbc8c647ac62438874e5795131.cpp\n       Creating library C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\n       \\Release\\sc_e013937dbc8c647ac62438874e5795131.lib and object C:\\DOCUME\n       ~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_e013937dbc8c64\n       7ac62438874e5795131.exp\n    1\n    
\n

\nNothing bad is happening, its just a bit annoying. Anyone know how to \nturn this off? \n

\nThis example also demonstrates using 'raw strings'. The r \npreceeding the code string in the last example denotes that this is a 'raw \nstring'. In raw strings, the backslash character is not interpreted as an \nescape character, and so it isn't necessary to use a double backslash to \nindicate that the '\\n' is meant to be interpreted in the C printf \nstatement instead of by Python. If your C code contains a lot\nof strings and control characters, raw strings might make things easier.\nMost of the time, however, standard strings work just as well.\n\n

\nThe printf statement in these examples is formatted to print \nout integers. What happens if a is a string? inline\nwill happily, compile a new version of the code to accept strings as input,\nand execute the code. The result?\n\n

    \n    >>> a = 'string'\n    >>> weave.inline(r'printf(\"%d\\n\",a);',['a'])\n    32956972\n    
\n

\nIn this case, the result is non-sensical, but also non-fatal. In other \nsituations, it might produce a compile time error because a is \nrequired to be an integer at some point in the code, or it could produce a \nsegmentation fault. Its possible to protect against passing \ninline arguments of the wrong data type by using asserts in \nPython.\n\n

    \n    >>> a = 'string'\n    >>> def protected_printf(a):    \n    ...     assert(type(a) == type(1))\n    ...     weave.inline(r'printf(\"%d\\n\",a);',['a'])\n    >>> protected_printf(1)\n     1\n    >>> protected_printf('string')\n    AssertError...\n    
\n\n

\nFor printing strings, the format statement needs to be changed. Also, weave\ndoesn't convert strings to char*. Instead it uses CXX Py::String type, so \nyou have to do a little more work. Here we convert it to a C++ std::string\nand then ask cor the char* version.\n\n

    \n    >>> a = 'string'    \n    >>> weave.inline(r'printf(\"%s\\n\",std::string(a).c_str());',['a'])\n    string\n    
\n

\n \nThis is a little convoluted. Perhaps strings should convert to std::string\nobjects instead of CXX objects. Or maybe to char*.\n\n\n

\nAs in this case, C/C++ code fragments often have to change to accept different \ntypes. For the given printing task, however, C++ streams provide a way of a \nsingle statement that works for integers and strings. By default, the stream \nobjects live in the std (standard) namespace and thus require the use of \nstd::.\n\n

    \n    >>> weave.inline('std::cout << a << std::endl;',['a'])\n    1    \n    >>> a = 'string'\n    >>> weave.inline('std::cout << a << std::endl;',['a'])\n    string\n    
\n \n

\nExamples using printf and cout are included in \nexamples/print_example.py.\n\n\n

More examples

\n\nThis section shows several more advanced uses of inline. It \nincludes a few algorithms from the Python Cookbook \nthat have been re-written in inline C to improve speed as well as a couple \nexamples using Numeric and wxPython.\n\n\n

Binary search

\nLets look at the example of searching a sorted list of integers for a value. \nFor inspiration, we'll use Kalle Svensson's \nbinary_search() algorithm from the Python Cookbook. His recipe follows:\n\n
\n    def binary_search(seq, t):\n        min = 0; max = len(seq) - 1\n        while 1:\n            if max < min:\n                return -1\n            m = (min  + max)  / 2\n            if seq[m] < t: \n                min = m  + 1 \n            elif seq[m] > t: \n                max = m  - 1 \n            else:\n                return m    \n    
\n\nThis Python version works for arbitrary Python data types. The C version below is \nspecialized to handle integer values. There is a little type checking done in \nPython to assure that we're working with the correct data types before heading \ninto C. The variables seq and t don't need to be \ndeclared beacuse weave handles converting and declaring them in \nthe C code. All other temporary variables such as min, max, etc. \nmust be declared -- it is C after all. Here's the new mixed Python/C function:\n\n
    \n    def c_int_binary_search(seq,t):\n        # do a little type checking in Python\n        assert(type(t) == type(1))\n        assert(type(seq) == type([]))\n        \n        # now the C code\n        code = \"\"\"\n               #line 29 \"binary_search.py\"\n               int val, m, min = 0;  \n               int max = seq.length() - 1;\n               PyObject *py_val; \n               for(;;)\n               {\n                   if (max < min  ) \n                   { \n                       return_val =  Py::new_reference_to(Py::Int(-1)); \n                       break;\n                   } \n                   m =  (min + max) /2;\n                   val =    py_to_int(PyList_GetItem(seq.ptr(),m),\"val\"); \n                   if (val  < t) \n                       min = m  + 1;\n                   else if (val >  t)\n                       max = m - 1;\n                   else\n                   {\n                       return_val = Py::new_reference_to(Py::Int(m));\n                       break;\n                   }\n               }\n               \"\"\"\n        return inline(code,['seq','t'])\n    
\n

\nWe have two variables seq and t passed in. \nt is guaranteed (by the assert) to be an integer. \nPython integers are converted to C int types in the transition from Python to \nC. seq is a Python list. By default, it is translated to a CXX \nlist object. Full documentation for the CXX library can be found at its website. The basics are that the CXX \nprovides C++ class equivalents for Python objects that simplify, or at \nleast object orientify, working with Python objects in C/C++. For example, \nseq.length() returns the length of the list. A little more about\nCXX and its class methods, etc. is in the ** type conversions ** section.\n

\n\nNote: CXX uses templates and therefore may be a little less portable than \nanother alternative by Gordan McMillan called SCXX which was inspired by\nCXX. It doesn't use templates so it should compile faster and be more portable.\nSCXX has a few less features, but it appears to me that it would mesh with\nthe needs of weave quite well. Hopefully xxx_spec files will be written\nfor SCXX in the future, and we'll be able to compare on a more empirical\nbasis. Both sets of spec files will probably stick around, it just a question\nof which becomes the default.\n\n

\nMost of the algorithm above looks similar in C to the original Python code. \nThere are two main differences. The first is the setting of \nreturn_val instead of directly returning from the C code with a \nreturn statement. return_val is an automatically \ndefined variable of type PyObject* that is returned from the C \ncode back to Python. You'll have to handle reference counting issues when \nsetting this variable. In this example, CXX classes and functions handle the \ndirty work. All CXX functions and classes live in the namespace \nPy::. The following code converts the integer m to a \nCXX Int() object and then to a PyObject* with an \nincremented reference count using Py::new_reference_to().\n\n

   \n    return_val = Py::new_reference_to(Py::Int(m));\n    
\n

\nThe second big differences shows up in the retrieval of integer values from the \nPython list. The simple Python seq[i] call balloons into a C \nPython API call to grab the value out of the list and then a separate call to \npy_to_int() that converts the PyObject* to an integer. \npy_to_int() includes both a NULL cheack and a \nPyInt_Check() call as well as the conversion call. If either of \nthe checks fail, an exception is raised. The entire C++ code block is executed \nwith in a try/catch block that handles exceptions much like Python \ndoes. This removes the need for most error checking code.\n

\nIt is worth note that CXX lists do have indexing operators that result \nin code that looks much like Python. However, the overhead in using them \nappears to be relatively high, so the standard Python API was used on the \nseq.ptr() which is the underlying PyObject* of the \nList object.\n

\nThe #line directive that is the first line of the C code \nblock isn't necessary, but it's nice for debugging. If the compilation fails \nbecause of the syntax error in the code, the error will be reported as an error \nin the Python file \"binary_search.py\" with an offset from the given line number \n(29 here).\n

\nSo what was all our effort worth in terms of efficiency? Well not a lot in \nthis case. The examples/binary_search.py file runs both Python and C versions \nof the functions As well as using the standard bisect module. If \nwe run it on a 1 million element list and run the search 3000 times (for 0-\n2999), here are the results we get:\n\n

   \n    C:\\home\\ej\\wrk\\scipy\\weave\\examples> python binary_search.py\n    Binary search for 3000 items in 1000000 length list of integers:\n     speed in python: 0.159999966621\n     speed of bisect: 0.121000051498\n     speed up: 1.32\n     speed in c: 0.110000014305\n     speed up: 1.45\n     speed in c(no asserts): 0.0900000333786\n     speed up: 1.78\n    
\n

\nSo, we get roughly a 50-75% improvement depending on whether we use the Python \nasserts in our C version. If we move down to searching a 10000 element list, \nthe advantage evaporates. Even smaller lists might result in the Python \nversion being faster. I'd like to say that moving to Numeric lists (and \ngetting rid of the GetItem() call) offers a substantial speed up, but my \npreliminary efforts didn't produce one. I think the log(N) algorithm is to \nblame. Because the algorithm is nice, there just isn't much time spent \ncomputing things, so moving to C isn't that big of a win. If there are ways to \nreduce conversion overhead of values, this may improve the C/Python speed \nup. Anyone have other explanations or faster code, please let me know.\n\n\n

Dictionary Sort

\n

\nThe demo in examples/dict_sort.py is another example from the Python CookBook. \nThis \nsubmission, by Alex Martelli, demonstrates how to return the values from a \ndictionary sorted by their keys:\n\n

       \n    def sortedDictValues3(adict):\n        keys = adict.keys()\n        keys.sort()\n        return map(adict.get, keys)\n    
\n

\nAlex provides 3 algorithms and this is the 3rd and fastest of the set. The C \nversion of this same algorithm follows:\n\n

       \n    def c_sort(adict):\n        assert(type(adict) == type({}))\n        code = \"\"\"     \n        #line 21 \"dict_sort.py\"  \n        Py::List keys = adict.keys();\n        Py::List items(keys.length()); keys.sort();     \n        PyObject* item = NULL; \n        for(int i = 0;  i < keys.length();i++)\n        {\n            item = PyList_GET_ITEM(keys.ptr(),i);\n            item = PyDict_GetItem(adict.ptr(),item);\n            Py_XINCREF(item);\n            PyList_SetItem(items.ptr(),i,item);              \n        }           \n        return_val = Py::new_reference_to(items);\n        \"\"\"   \n        return inline_tools.inline(code,['adict'],verbose=1)\n    
\n

\nLike the original Python function, the C++ version can handle any Python \ndictionary regardless of the key/value pair types. It uses CXX objects for the \nmost part to declare python types in C++, but uses Python API calls to manipulate \ntheir contents. Again, this choice is made for speed. The C++ version, while\nmore complicated, is about a factor of 2 faster than Python.\n\n

       \n    C:\\home\\ej\\wrk\\scipy\\weave\\examples> python dict_sort.py\n    Dict sort of 1000 items for 300 iterations:\n     speed in python: 0.319999933243\n    [0, 1, 2, 3, 4]\n     speed in c: 0.151000022888\n     speed up: 2.12\n    [0, 1, 2, 3, 4]\n    
\n

\n\n

Numeric -- cast/copy/transpose

\n\nCastCopyTranspose is a function called quite heavily by Linear Algebra routines\nin the Numeric library. Its needed in part because of the row-major memory layout\nof multi-demensional Python (and C) arrays vs. the col-major order of the underlying\nFortran algorithms. For small matrices (say 100x100 or less), a significant\nportion of the common routines such as LU decompisition or singular value decompostion\nare spent in this setup routine. This shouldn't happen. Here is the Python\nversion of the function using standard Numeric operations.\n\n
       \n    def _castCopyAndTranspose(type, array):\n        if a.typecode() == type:\n            cast_array = copy.copy(Numeric.transpose(a))\n        else:\n            cast_array = copy.copy(Numeric.transpose(a).astype(type))\n        return cast_array\n    
\n\nAnd the following is a inline C version of the same function:\n\n
\n    from weave.blitz_tools import blitz_type_factories\n    from weave import scalar_spec\n    from weave import inline\n    def _cast_copy_transpose(type,a_2d):\n        assert(len(shape(a_2d)) == 2)\n        new_array = zeros(shape(a_2d),type)\n        numeric_type = scalar_spec.numeric_to_blitz_type_mapping[type]\n        code = \\\n        \"\"\"  \n        for(int i = 0;i < _Na_2d[0]; i++)  \n            for(int j = 0;  j < _Na_2d[1]; j++)\n                new_array(i,j) = (%s) a_2d(j,i);\n        \"\"\" % numeric_type\n        inline(code,['new_array','a_2d'],\n               type_factories = blitz_type_factories,compiler='gcc')\n        return new_array\n    
\n\nThis example uses blitz++ arrays instead of the standard representation of \nNumeric arrays so that indexing is simplier to write. This is accomplished by \npassing in the blitz++ \"type factories\" to override the standard Python to C++ \ntype conversions. Blitz++ arrays allow you to write clean, fast code, but they \nalso are sloooow to compile (20 seconds or more for this snippet). This is why \nthey aren't the default type used for Numeric arrays (and also because most \ncompilers can't compile blitz arrays...). inline() is also forced \nto use 'gcc' as the compiler because the default compiler on Windows (MSVC) \nwill not compile blitz code. 'gcc' I think will use the standard compiler \non Unix machine instead of explicitly forcing gcc (check this) \n\nComparisons of the Python vs inline C++ code show a factor of 3 speed up. Also \nshown are the results of an \"inplace\" transpose routine that can be used if the \noutput of the linear algebra routine can overwrite the original matrix (this is \noften appropriate). This provides another factor of 2 improvement.\n\n
\n     #C:\\home\\ej\\wrk\\scipy\\weave\\examples> python cast_copy_transpose.py\n    # Cast/Copy/Transposing (150,150)array 1 times\n    #  speed in python: 0.870999932289\n    #  speed in c: 0.25\n    #  speed up: 3.48\n    #  inplace transpose c: 0.129999995232\n    #  speed up: 6.70\n    
\n\n\n

wxPython

\n\ninline knows how to handle wxPython objects. Thats nice in and of\nitself, but it also demonstrates that the type conversion mechanism is reasonably \nflexible. Chances are, it won't take a ton of effort to support special types\nyou might have. The examples/wx_example.py borrows the scrolled window\nexample from the wxPython demo, accept that it mixes inline C code in the middle\nof the drawing function.\n\n
\n    def DoDrawing(self, dc):\n        \n        red = wxNamedColour(\"RED\");\n        blue = wxNamedColour(\"BLUE\");\n        grey_brush = wxLIGHT_GREY_BRUSH;\n        code = \\\n        \"\"\"\n        #line 108 \"wx_example.py\" \n        dc->BeginDrawing();\n        dc->SetPen(wxPen(*red,4,wxSOLID));\n        dc->DrawRectangle(5,5,50,50);\n        dc->SetBrush(*grey_brush);\n        dc->SetPen(wxPen(*blue,4,wxSOLID));\n        dc->DrawRectangle(15, 15, 50, 50);\n        \"\"\"\n        inline(code,['dc','red','blue','grey_brush'])\n        \n        dc.SetFont(wxFont(14, wxSWISS, wxNORMAL, wxNORMAL))\n        dc.SetTextForeground(wxColour(0xFF, 0x20, 0xFF))\n        te = dc.GetTextExtent(\"Hello World\")\n        dc.DrawText(\"Hello World\", 60, 65)\n\n        dc.SetPen(wxPen(wxNamedColour('VIOLET'), 4))\n        dc.DrawLine(5, 65+te[1], 60+te[0], 65+te[1])\n        ...\n    
\n\nHere, some of the Python calls to wx objects were just converted to C++ calls. There\nisn't any benefit, it just demonstrates the capabilities. You might want to use this\nif you have a computationally intensive loop in your drawing code that you want to \nspeed up.\n\nOn windows, you'll have to use the MSVC compiler if you use the standard wxPython\nDLLs distributed by Robin Dunn. Thats because MSVC and gcc, while binary\ncompatible in C, are not binary compatible for C++. In fact, its probably best, no \nmatter what platform you're on, to specify that inline use the same\ncompiler that was used to build wxPython to be on the safe side. There isn't currently\na way to learn this info from the library -- you just have to know. Also, at least\non the windows platform, you'll need to install the wxWindows libraries and link to \nthem. I think there is a way around this, but I haven't found it yet -- I get some\nlinking errors dealing with wxString. One final note. You'll probably have to\ntweak weave/wx_spec.py or weave/wx_info.py for your machine's configuration to\npoint at the correct directories etc. There. That should sufficiently scare people\ninto not even looking at this... :)\n\n
\n

Keyword Options

\n

\nThe basic definition of the inline() function has a slew of \noptional variables. It also takes keyword arguments that are passed to \ndistutils as compiler options. The following is a formatted \ncut/paste of the argument section of inline's doc-string. It \nexplains all of the variables. Some examples using various options will \nfollow.\n\n

       \n    def inline(code,arg_names,local_dict = None, global_dict = None, \n               force = 0, \n               compiler='',\n               verbose = 0, \n               support_code = None,\n               customize=None, \n               type_factories = None, \n               auto_downcast=1,\n               **kw):\n    
\n\n \ninline has quite \na few options as listed below. Also, the keyword arguments for distutils \nextension modules are accepted to specify extra information needed for \ncompiling. \n
\n

inline Arguments:

\n
\n
\n
code
\n \n
\nstring. A string of valid C++ code. It should not \n specify a return statement. Instead it should assign results that need to be \n returned to Python in the return_val. \n
\n\n
arg_names
\n \n
\nlist of strings. A list of Python variable names \n that should be transferred from Python into the C/C++ code. \n
\n\n
local_dict
\n \n
\noptional. dictionary. If specified, it is a \n dictionary of values that should be used as the local scope for the C/C++ \n code. If local_dict is not specified the local dictionary of the calling \n function is used. \n
\n\n
global_dict
\n \n
\noptional. dictionary. If specified, it is a \n dictionary of values that should be used as the global scope for the C/C++ \n code. If global_dict is not specified the global dictionary of the calling \n function is used. \n
\n\n
force
\n \n
\noptional. 0 or 1. default 0. If 1, the C++ code is \n compiled every time inline is called. This is really only useful for \n debugging, and probably only useful if you're editing support_code a lot. \n
\n\n
compiler
\n \n
\noptional. string. The name of compiler to use when compiling. On windows, it \nunderstands 'msvc' and 'gcc' as well as all the compiler names understood by \ndistutils. On Unix, it'll only understand the values understoof by distutils. \n(I should add 'gcc' though to this).\n

\nOn windows, the compiler defaults to the Microsoft C++ compiler. If this isn't \navailable, it looks for mingw32 (the gcc compiler).\n

\nOn Unix, it'll probably use the same compiler that was used when compiling \nPython. Cygwin's behavior should be similar.

\n
\n\n
verbose
\n \n
\noptional. 0,1, or 2. defualt 0. Speficies how much \n much information is printed during the compile phase of inlining code. 0 is \n silent (except on windows with msvc where it still prints some garbage). 1 \n informs you when compiling starts, finishes, and how long it took. 2 prints \n out the command lines for the compilation process and can be useful if you're \n having problems getting code to work. Its handy for finding the name of the \n .cpp file if you need to examine it. verbose has no affect if the \n compilation isn't necessary. \n
\n\n
support_code
\n \n
\noptional. string. A string of valid C++ code \n declaring extra code that might be needed by your compiled function. This \n could be declarations of functions, classes, or structures. \n
\n\n
customize
\n \n
\noptional. base_info.custom_info object. An \n alternative way to specifiy support_code, headers, etc. needed by the \n function see the weave.base_info module for more details. (not sure \n this'll be used much). \n \n
\n
type_factories
\n \n
\noptional. list of type specification factories. These guys are what convert \nPython data types to C/C++ data types. If you'd like to use a different set of \ntype conversions than the default, specify them here. Look in the type \nconversions section of the main documentation for examples.\n
\n
auto_downcast
\n \n
\noptional. 0 or 1. default 1. This only affects functions that have Numeric \narrays as input variables. Setting this to 1 will cause all floating point \nvalues to be cast as float instead of double if all the Numeric arrays are of \ntype float. If even one of the arrays has type double or double complex, all \nvariables maintain there standard types.\n
\n
\n
\n\n

Distutils keywords:

\n
\ninline() also accepts a number of distutils keywords \nfor controlling how the code is compiled. The following descriptions have been \ncopied from Greg Ward's distutils.extension.Extension class doc-\nstrings for convenience:\n\n
\n
sources
\n \n
\n[string] list of source filenames, relative to the \n distribution root (where the setup script lives), in Unix form \n (slash-separated) for portability. Source files may be C, C++, SWIG (.i), \n platform-specific resource files, or whatever else is recognized by the \n \"build_ext\" command as source for a Python extension. Note: The module_path \n file is always appended to the front of this list \n
\n\n
include_dirs
\n \n
\n[string] list of directories to search for C/C++ \n header files (in Unix form for portability) \n
\n\n
define_macros
\n \n
\n[(name : string, value : string|None)] list of \n macros to define; each macro is defined using a 2-tuple, where 'value' is \n either the string to define it to or None to define it without a particular \n value (equivalent of \"#define FOO\" in source or -DFOO on Unix C compiler \n command line) \n
\n
undef_macros
\n \n
\n[string] list of macros to undefine explicitly \n
\n
library_dirs
\n
\n[string] list of directories to search for C/C++ libraries at link time \n
\n
libraries
\n
\n[string] list of library names (not filenames or paths) to link against \n
\n
runtime_library_dirs
\n
\n[string] list of directories to search for C/C++ libraries at run time (for \nshared extensions, this is when the extension is loaded) \n
\n\n
extra_objects
\n \n
\n[string] list of extra files to link with (eg. \n object files not implied by 'sources', static library that must be \n explicitly specified, binary resource files, etc.) \n
\n\n
extra_compile_args
\n \n
\n[string] any extra platform- and compiler-specific \n information to use when compiling the source files in 'sources'. For \n platforms and compilers where \"command line\" makes sense, this is typically \n a list of command-line arguments, but for other platforms it could be \n anything. \n
\n
extra_link_args
\n \n
\n[string] any extra platform- and compiler-specific \n information to use when linking object files together to create the \n extension (or to create a new static Python interpreter). Similar \n interpretation as for 'extra_compile_args'. \n
\n
export_symbols
\n \n
\n[string] list of symbols to be exported from a shared extension. Not used on \nall platforms, and not generally necessary for Python extensions, which \ntypically export exactly one symbol: \"init\" + extension_name. \n
\n
\n
\n\n\n

Keyword Option Examples

\nWe'll walk through several examples here to demonstrate the behavior of \ninline and also how the various arguments are used.\n\nIn the simplest (most) cases, code and arg_names\nare the only arguments that need to be specified. Here's a simple example\nrun on Windows machine that has Microsoft VC++ installed.\n\n
\n    >>> from weave import inline\n    >>> a = 'string'\n    >>> code = \"\"\"\n    ...        int l = a.length();\n    ...        return_val = Py::new_reference_to(Py::Int(l));\n    ...        \"\"\"\n    >>> inline(code,['a'])\n     sc_86e98826b65b047ffd2cd5f479c627f12.cpp\n    Creating\n       library C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e98826b65b047ffd2cd5f479c627f12.lib\n    and object C:\\DOCUME~ 1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e98826b65b047ff\n    d2cd5f479c627f12.exp\n    6\n    >>> inline(code,['a'])\n    6\n    
\n \nWhen inline is first run, you'll notice that pause and some \ntrash printed to the screen. The \"trash\" is acutually part of the compilers\noutput that distutils does not supress. The name of the extension file, \nsc_bighonkingnumber.cpp, is generated from the md5 check sum\nof the C/C++ code fragment. On Unix or windows machines with only\ngcc installed, the trash will not appear. On the second call, the code \nfragment is not compiled since it already exists, and only the answer is \nreturned. Now kill the interpreter and restart, and run the same code with\na different string.\n\n
\n    >>> from weave import inline\n    >>> a = 'a longer string' \n    >>> code = \"\"\" \n    ...        int l = a.length();\n    ...        return_val = Py::new_reference_to(Py::Int(l));  \n    ...        \"\"\"\n    >>> inline(code,['a'])\n    15\n    
\n

\nNotice this time, inline() did not recompile the code because it\nfound the compiled function in the persistent catalog of functions. There is\na short pause as it looks up and loads the function, but it is much shorter \nthan compiling would require.\n

\nYou can specify the local and global dictionaries if you'd like (much like \nexec or eval() in Python), but if they aren't \nspecified, the \"expected\" ones are used -- i.e. the ones from the function that \ncalled inline() . This is accomplished through a little call \nframe trickery. Here is an example where the local_dict is specified using\nthe same code example from above:\n\n

\n    >>> a = 'a longer string'\n    >>> b = 'an even  longer string' \n    >>> my_dict = {'a':b}\n    >>> inline(code,['a'])\n    15\n    >>> inline(code,['a'],my_dict)\n    21\n    
\n \n

\nEverytime, the code is changed, inline does a \nrecompile. However, changing any of the other options in inline does not\nforce a recompile. The force option was added so that one\ncould force a recompile when tinkering with other variables. In practice,\nit is just as easy to change the code by a single character\n(like adding a space some place) to force the recompile. Note: It also \nmight be nice to add some methods for purging the cache and on disk \ncatalogs.\n

\nI use verbose sometimes for debugging. When set to 2, it'll \noutput all the information (including the name of the .cpp file) that you'd\nexpect from running a make file. This is nice if you need to examine the\ngenerated code to see where things are going haywire. Note that error\nmessages from failed compiles are printed to the screen even if verbose\n is set to 0.\n

\nThe following example demonstrates using gcc instead of the standard msvc \ncompiler on windows using same code fragment as above. Because the example has \nalready been compiled, the force=1 flag is needed to make \ninline() ignore the previously compiled version and recompile \nusing gcc. The verbose flag is added to show what is printed out:\n\n

\n    >>>inline(code,['a'],compiler='gcc',verbose=2,force=1)\n    running build_ext    \n    building 'sc_86e98826b65b047ffd2cd5f479c627f13' extension \n    c:\\gcc-2.95.2\\bin\\g++.exe -mno-cygwin -mdll -O2 -w -Wstrict-prototypes -IC:\n    \\home\\ej\\wrk\\scipy\\weave -IC:\\Python21\\Include -c C:\\DOCUME~1\\eric\\LOCAL\n    S~1\\Temp\\python21_compiled\\sc_86e98826b65b047ffd2cd5f479c627f13.cpp -o C:\\D\n    OCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e98826b65b04\n    7ffd2cd5f479c627f13.o    \n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\cxxextensions.c (C:\\DOCUME~1\\eri\n    c\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\cxxextensions.o up-to-date)\n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\cxxsupport.cxx (C:\\DOCUME~1\\eric\n    \\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\cxxsupport.o up-to-date)\n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\IndirectPythonInterface.cxx (C:\\\n    DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\indirectpythonin\n    terface.o up-to-date)\n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\cxx_extensions.cxx (C:\\DOCUME~1\\\n    eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\cxx_extensions.o up-to-da\n    te)\n    writing C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86\n    e98826b65b047ffd2cd5f479c627f13.def\n    c:\\gcc-2.95.2\\bin\\dllwrap.exe --driver-name g++ -mno-cygwin -mdll -static -\n    -output-lib C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\l\n    ibsc_86e98826b65b047ffd2cd5f479c627f13.a --def C:\\DOCUME~1\\eric\\LOCALS~1\\Te\n    mp\\python21_compiled\\temp\\Release\\sc_86e98826b65b047ffd2cd5f479c627f13.def \n    -s C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e9882\n    6b65b047ffd2cd5f479c627f13.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compil\n    ed\\temp\\Release\\cxxextensions.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_com\n    piled\\temp\\Release\\cxxsupport.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_com\n    piled\\temp\\Release\\indirectpythoninterface.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\n    \\python21_compiled\\temp\\Release\\cxx_extensions.o -LC:\\Python21\\libs -lpytho\n    n21 -o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\sc_86e98826b65b047f\n    fd2cd5f479c627f13.pyd\n    15\n    
\n\nThat's quite a bit of output. verbose=1 just prints the compile\ntime.\n\n
\n    >>>inline(code,['a'],compiler='gcc',verbose=1,force=1)\n    Compiling code...\n    finished compiling (sec):  6.00800001621\n    15\n    
\n\n

\n Note: I've only used the compiler option for switching between 'msvc'\nand 'gcc' on windows. It may have use on Unix also, but I don't know yet.\n\n\n

\nThe support_code argument is likely to be used a lot. It allows \nyou to specify extra code fragments such as function, structure or class \ndefinitions that you want to use in the code string. Note that \nchanges to support_code do not force a recompile. The \ncatalog only relies on code (for performance reasons) to determine \nwhether recompiling is necessary. So, if you make a change to support_code, \nyou'll need to alter code in some way or use the \nforce argument to get the code to recompile. I usually just add \nsome inocuous whitespace to the end of one of the lines in code \nsomewhere. Here's an example of defining a separate method for calculating\nthe string length:\n\n

\n    >>> from weave import inline\n    >>> a = 'a longer string'\n    >>> support_code = \"\"\"\n    ...                PyObject* length(Py::String a)\n    ...                {\n    ...                    int l = a.length();  \n    ...                    return Py::new_reference_to(Py::Int(l)); \n    ...                }\n    ...                \"\"\"        \n    >>> inline(\"return_val = length(a);\",['a'],\n    ...        support_code = support_code)\n    15\n    
\n

\ncustomize is a left over from a previous way of specifying \ncompiler options. It is a custom_info object that can specify \nquite a bit of information about how a file is compiled. These \ninfo objects are the standard way of defining compile information \nfor type conversion classes. However, I don't think they are as handy here, \nespecially since we've exposed all the keyword arguments that distutils can \nhandle. Between these keywords, and the support_code option, I \nthink customize may be obsolete. We'll see if anyone cares to use \nit. If not, it'll get axed in the next version.\n

\nThe type_factories variable is important to people who want to\ncustomize the way arguments are converted from Python to C. We'll talk about\nthis in the next chapter **xx** of this document when we discuss type\nconversions.\n

\nauto_downcast handles one of the big type conversion issues that\nis common when using Numeric arrays in conjunction with Python scalar values.\nIf you have an array of single precision values and multiply that array by a \nPython scalar, the result is upcast to a double precision array because the\nscalar value is double precision. This is not usually the desired behavior\nbecause it can double your memory usage. auto_downcast goes\nsome distance towards changing the casting precedence of arrays and scalars.\nIf your only using single precision arrays, it will automatically downcast all\nscalar values from double to single precision when they are passed into the\nC++ code. This is the default behavior. If you want all values to keep there\ndefault type, set auto_downcast to 0.\n

\n\n\n\n

Returning Values

\n\nPython variables in the local and global scope transfer seemlessly from Python \ninto the C++ snippets. And, if inline were to completely live up\nto its name, any modifications to variables in the C++ code would be reflected\nin the Python variables when control was passed back to Python. For example,\nthe desired behavior would be something like:\n\n
\n    # THIS DOES NOT WORK\n    >>> a = 1\n    >>> weave.inline(\"a++;\",['a'])\n    >>> a\n    2\n    
\n\nInstead you get:\n\n
\n    >>> a = 1\n    >>> weave.inline(\"a++;\",['a'])\n    >>> a\n    1\n    
\n \nVariables are passed into C++ as if you are calling a Python function. Python's \ncalling convention is sometimes called \"pass by assignment\". This means its as \nif a c_a = a assignment is made right before inline \ncall is made and the c_a variable is used within the C++ code. \nThus, any changes made to c_a are not reflected in Python's \na variable. Things do get a little more confusing, however, when \nlooking at variables with mutable types. Changes made in C++ to the contents \nof mutable types are reflected in the Python variables.\n\n
\n    >>> a= [1,2]\n    >>> weave.inline(\"PyList_SetItem(a.ptr(),0,PyInt_FromLong(3));\",['a'])\n    >>> print a\n    [3, 2]\n    
\n\nSo modifications to the contents of mutable types in C++ are seen when control\nis returned to Python. Modifications to immutable types such as tuples,\nstrings, and numbers do not alter the Python variables.\n\nIf you need to make changes to an immutable variable, you'll need to assign\nthe new value to the \"magic\" variable return_val in C++. This\nvalue is returned by the inline() function:\n\n
\n    >>> a = 1\n    >>> a = weave.inline(\"return_val = Py::new_reference_to(Py::Int(a+1));\",['a'])  \n    >>> a\n    2\n    
\n\nThe return_val variable can also be used to return newly created \nvalues. This is possible by returning a tuple. The following trivial example \nillustrates how this can be done:\n\n
       \n    # python version\n    def multi_return():\n        return 1, '2nd'\n    \n    # C version.\n    def c_multi_return():    \n        code =  \"\"\"\n     \t        Py::Tuple results(2);\n     \t        results[0] = Py::Int(1);\n     \t        results[1] = Py::String(\"2nd\");\n     \t        return_val = Py::new_reference_to(results); \t        \n                \"\"\"\n        return inline_tools.inline(code)\n    
\n

\nThe example is available in examples/tuple_return.py. It also\nhas the dubious honor of demonstrating how much inline() can \nslow things down. The C version here is about 10 times slower than the Python\nversion. Of course, something so trivial has no reason to be written in\nC anyway.\n\n\n

The issue with locals()

\n

\ninline passes the locals() and globals() \ndictionaries from Python into the C++ function from the calling function. It \nextracts the variables that are used in the C++ code from these dictionaries, \nconverts then to C++ variables, and then calculates using them. It seems like \nit would be trivial, then, after the calculations were finished to then insert \nthe new values back into the locals() and globals() \ndictionaries so that the modified values were reflected in Python. \nUnfortunately, as pointed out by the Python manual, the locals() dictionary is \nnot writable. \n

\n\nI suspect locals() is not writable because there are some \noptimizations done to speed lookups of the local namespace. I'm guessing local \nlookups don't always look at a dictionary to find values. Can someone \"in the \nknow\" confirm or correct this? Another thing I'd like to know is whether there \nis a way to write to the local namespace of another stack frame from C/C++. If \nso, it would be possible to have some clean up code in compiled functions that \nwrote final values of variables in C++ back to the correct Python stack frame. \nI think this goes a long way toward making inline truely live up \nto its name. I don't think we'll get to the point of creating variables in \nPython for variables created in C -- although I suppose with a C/C++ parser you \ncould do that also.\n\n

\n\n\n

A quick look at the code

\n\nweave generates a C++ file holding an extension function for \neach inline code snippet. These file names are generated using \nfrom the md5 signature of the code snippet and saved to a location specified by \nthe PYTHONCOMPILED environment variable (discussed later). The cpp files are \ngenerally about 200-400 lines long and include quite a few functions to support \ntype conversions, etc. However, the actual compiled function is pretty simple. \nBelow is the familiar printf example:\n\n
\n    >>> import weave    \n    >>> a = 1\n    >>> weave.inline('printf(\"%d\\\\n\",a);',['a'])\n    1\n    
\n\nAnd here is the extension function generated by inline:\n\n
\n    static PyObject* compiled_func(PyObject*self, PyObject* args)\n    {\n        // The Py_None needs an incref before returning\n        PyObject *return_val = NULL;\n        int exception_occured = 0;\n        PyObject *py__locals = NULL;\n        PyObject *py__globals = NULL;\n        PyObject *py_a;\n        py_a = NULL;\n        \n        if(!PyArg_ParseTuple(args,\"OO:compiled_func\",&py__locals,&py__globals))\n            return NULL;\n        try                              \n        {                                \n            PyObject* raw_locals = py_to_raw_dict(py__locals,\"_locals\");\n            PyObject* raw_globals = py_to_raw_dict(py__globals,\"_globals\");\n            int a = py_to_int (get_variable(\"a\",raw_locals,raw_globals),\"a\");\n            /* Here is the inline code */            \n            printf(\"%d\\n\",a);\n            /* I would like to fill in changed locals and globals here... */\n        }                                       \n        catch( Py::Exception& e)           \n        {                                \n            return_val =  Py::Null();    \n            exception_occured = 1;       \n        }                                 \n        if(!return_val && !exception_occured)\n        {\n                                      \n            Py_INCREF(Py_None);              \n            return_val = Py_None;            \n        }\n        /* clean up code */\n        \n        /* return */                              \n        return return_val;           \n    }                                \n    
\n\nEvery inline function takes exactly two arguments -- the local and global\ndictionaries for the current scope. All variable values are looked up out\nof these dictionaries. The lookups, along with all inline code \nexecution, are done within a C++ try block. If the variables\naren't found, or there is an error converting a Python variable to the \nappropriate type in C++, an exception is raised. The C++ exception\nis automatically converted to a Python exception by CXX and returned to Python.\n\nThe py_to_int() function illustrates how the conversions and\nexception handling works. py_to_int first checks that the given PyObject*\npointer is not NULL and is a Python integer. If all is well, it calls the\nPython API to convert the value to an int. Otherwise, it calls\nhandle_bad_type() which gathers information about what went wrong\nand then raises a CXX TypeError which returns to Python as a TypeError.\n\n
\n    int py_to_int(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyInt_Check(py_obj))\n            handle_bad_type(py_obj,\"int\", name);\n        return (int) PyInt_AsLong(py_obj);\n    }\n    
\n\n
\n    void handle_bad_type(PyObject* py_obj, char* good_type, char*  var_name)\n    {\n        char msg[500];\n        sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n                find_type(py_obj),good_type,var_name);\n        throw Py::TypeError(msg);\n    }\n    \n    char* find_type(PyObject* py_obj)\n    {\n        if(py_obj == NULL) return \"C NULL value\";\n        if(PyCallable_Check(py_obj)) return \"callable\";\n        if(PyString_Check(py_obj)) return \"string\";\n        if(PyInt_Check(py_obj)) return \"int\";\n        if(PyFloat_Check(py_obj)) return \"float\";\n        if(PyDict_Check(py_obj)) return \"dict\";\n        if(PyList_Check(py_obj)) return \"list\";\n        if(PyTuple_Check(py_obj)) return \"tuple\";\n        if(PyFile_Check(py_obj)) return \"file\";\n        if(PyModule_Check(py_obj)) return \"module\";\n        \n        //should probably do more interagation (and thinking) on these.\n        if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n        if(PyInstance_Check(py_obj)) return \"instance\"; \n        if(PyCallable_Check(py_obj)) return \"callable\";\n        return \"unkown type\";\n    }\n    
\n\nSince the inline is also executed within the try/catch\nblock, you can use CXX exceptions within your code. It is usually a bad idea\nto directly return from your code, even if an error occurs. This\nskips the clean up section of the extension function. In this simple example,\nthere isn't any clean up code, but in more complicated examples, there may\nbe some reference counting that needs to be taken care of here on converted\nvariables. To avoid this, either uses exceptions or set \nreturn_val to NULL and use if/then's to skip code\nafter errors.\n\n\n

Technical Details

\n

\nThere are several main steps to using C/C++ code withing Python:\n

    \n
  1. Type conversion \n
  2. Generating C/C++ code \n
  3. Compile the code to an extension module \n
  4. Catalog (and cache) the function for future use
  5. \n
\n

\nItems 1 and 2 above are related, but most easily discussed separately. Type \nconversions are customizable by the user if needed. Understanding them is \npretty important for anything beyond trivial uses of inline. \nGenerating the C/C++ code is handled by ext_function and \next_module classes and . For the most part, compiling the code is \nhandled by distutils. Some customizations were needed, but they were \nrelatively minor and do not require changes to distutils itself. Cataloging is \npretty simple in concept, but surprisingly required the most code to implement \n(and still likely needs some work). So, this section covers items 1 and 4 from \nthe list. Item 2 is covered later in the chapter covering the \next_tools module, and distutils is covered by a completely \nseparate document xxx.\n\n

Passing Variables in/out of the C/C++ code

\n\nNote: Passing variables into the C code is pretty straight forward, but there \nare subtlties to how variable modifications in C are returned to Python. see Returning Values for a more thorough discussion of \nthis issue.\n \n \n\n

Type Conversions

\n\n\nNote: Maybe xxx_converter instead of \nxxx_specification is a more descriptive name. Might change in \nfuture version?\n\n\n

\nBy default, inline() makes the following type conversions between\nPython and C++ types.\n

\n\n

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n

Default Data Type Conversions

\n

Python

\n

C++

   int   int
   float   double
   complex   std::complex
   string   Py::String
   list   Py::List
   dict   Py::Dict
   tuple   Py::Tuple
   file   FILE*
   callable   PyObject*
   instance   PyObject*
   Numeric.array   PyArrayObject*
   wxXXX   wxXXX*
\n
\n

\nThe Py:: namespace is defined by the \nCXX library which has C++ class\nequivalents for many Python types. std:: is the namespace of the\nstandard library in C++.\n

\n\nNote: \n

\n\n

\n\nPython to C++ conversions fill in code in several locations in the generated\ninline extension function. Below is the basic template for the\nfunction. This is actually the exact code that is generated by calling\nweave.inline(\"\").\n\n

\n    static PyObject* compiled_func(PyObject*self, PyObject* args)\n    {\n        PyObject *return_val = NULL;\n        int exception_occured = 0;\n        PyObject *py__locals = NULL;\n        PyObject *py__globals = NULL;\n        PyObject *py_a;\n        py_a = NULL;\n    \n        if(!PyArg_ParseTuple(args,\"OO:compiled_func\",&py__locals,&py__globals))\n            return NULL;\n        try\n        {\n            PyObject* raw_locals = py_to_raw_dict(py__locals,\"_locals\");\n            PyObject* raw_globals = py_to_raw_dict(py__globals,\"_globals\");\n            /* argument conversion code */\n            /* inline code */\n            /*I would like to fill in changed locals and globals here...*/\n    \n        }\n        catch( Py::Exception& e)\n        {\n            return_val =  Py::Null();\n            exception_occured = 1;\n        }\n        /* cleanup code */\n        if(!return_val && !exception_occured)\n        {\n    \n            Py_INCREF(Py_None);\n            return_val = Py_None;\n        }\n    \n        return return_val;\n    }\n    
\n\nThe /* inline code */ section is filled with the code passed to\nthe inline() function call. The \n/*argument convserion code*/ and /* cleanup code */\nsections are filled with code that handles conversion from Python to C++\ntypes and code that deallocates memory or manipulates reference counts before\nthe function returns. The following sections demostrate how these two areas\nare filled in by the default conversion methods.\n\n \nNote: I'm not sure I have reference counting correct on a few of these. The \nonly thing I increase/decrease the ref count on is Numeric arrays. If you\nsee an issue, please let me know.\n\n\n\n

Numeric Argument Conversion

\n\nInteger, floating point, and complex arguments are handled in a very similar\nfashion. Consider the following inline function that has a single integer \nvariable passed in:\n\n
\n    >>> a = 1\n    >>> inline(\"\",['a'])\n    
\n\nThe argument conversion code inserted for a is:\n\n
\n    /* argument conversion code */\n    int a = py_to_int (get_variable(\"a\",raw_locals,raw_globals),\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. py_to_int() has the following\nform:\n\n
\n    static int py_to_int(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyInt_Check(py_obj))\n            handle_bad_type(py_obj,\"int\", name);\n        return (int) PyInt_AsLong(py_obj);\n    }\n    
\n\nSimilarly, the float and complex conversion routines look like:\n\n
    \n    static double py_to_float(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyFloat_Check(py_obj))\n            handle_bad_type(py_obj,\"float\", name);\n        return PyFloat_AsDouble(py_obj);\n    }\n    \n    static std::complex py_to_complex(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyComplex_Check(py_obj))\n            handle_bad_type(py_obj,\"complex\", name);\n        return std::complex(PyComplex_RealAsDouble(py_obj),\n                                    PyComplex_ImagAsDouble(py_obj));    \n    }\n    
\n\nNumeric conversions do not require any clean up code.\n\n\n

String, List, Tuple, and Dictionary Conversion

\n\nStrings, Lists, Tuples and Dictionary conversions are all converted to \nCXX types by default.\n\nFor the following code, \n\n
\n    >>> a = [1]\n    >>> inline(\"\",['a'])\n    
\n\nThe argument conversion code inserted for a is:\n\n
\n    /* argument conversion code */\n    Py::List a = py_to_list (get_variable(\"a\",raw_locals,raw_globals),\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. py_to_list() and its\nfriends has the following form:\n\n
    \n    static Py::List py_to_list(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyList_Check(py_obj))\n            handle_bad_type(py_obj,\"list\", name);\n        return Py::List(py_obj);\n    }\n    \n    static Py::String py_to_string(PyObject* py_obj,char* name)\n    {\n        if (!PyString_Check(py_obj))\n            handle_bad_type(py_obj,\"string\", name);\n        return Py::String(py_obj);\n    }\n\n    static Py::Dict py_to_dict(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyDict_Check(py_obj))\n            handle_bad_type(py_obj,\"dict\", name);\n        return Py::Dict(py_obj);\n    }\n    \n    static Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyTuple_Check(py_obj))\n            handle_bad_type(py_obj,\"tuple\", name);\n        return Py::Tuple(py_obj);\n    }\n    
\n\nCXX handles reference counts on for strings, lists, tuples, and dictionaries,\nso clean up code isn't necessary.\n\n\n

File Conversion

\n\nFor the following code, \n\n
\n    >>> a = open(\"bob\",'w')  \n    >>> inline(\"\",['a'])\n    
\n\nThe argument conversion code is:\n\n
\n    /* argument conversion code */\n    PyObject* py_a = get_variable(\"a\",raw_locals,raw_globals);\n    FILE* a = py_to_file(py_a,\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. py_to_file() converts\nPyObject* to a FILE* and increments the reference count of the PyObject*:\n\n
\n    FILE* py_to_file(PyObject* py_obj, char* name)\n    {\n        if (!py_obj || !PyFile_Check(py_obj))\n            handle_bad_type(py_obj,\"file\", name);\n    \n        Py_INCREF(py_obj);\n        return PyFile_AsFile(py_obj);\n    }\n    
\n\nBecause the PyObject* was incremented, the clean up code needs to decrement\nthe counter\n\n
\n    /* cleanup code */\n    Py_XDECREF(py_a);\n    
\n\nIts important to understand that file conversion only works on actual files --\ni.e. ones created using the open() command in Python. It does\nnot support converting arbitrary objects that support the file interface into\nC FILE* pointers. This can affect many things. For example, in\ninitial printf() examples, one might be tempted to solve the \nproblem of C and Python IDE's (PythonWin, PyCrust, etc.) writing to different\nstdout and stderr by using fprintf() and passing in \nsys.stdout and sys.stderr. For example, instead of\n\n
\n    >>> weave.inline('printf(\"hello\\\\n\");')\n    
\n \nYou might try:\n\n
\n    >>> buf = sys.stdout\n    >>> weave.inline('fprintf(buf,\"hello\\\\n\");',['buf'])\n    
\n\nThis will work as expected from a standard python interpreter, but in PythonWin,\nthe following occurs:\n\n
\n    >>> buf = sys.stdout\n    >>> weave.inline('fprintf(buf,\"hello\\\\n\");',['buf'])\n    Traceback (most recent call last):\n        File \"\", line 1, in ?\n        File \"C:\\Python21\\weave\\inline_tools.py\", line 315, in inline\n            auto_downcast = auto_downcast,\n        File \"C:\\Python21\\weave\\inline_tools.py\", line 386, in compile_function\n            type_factories = type_factories)\n        File \"C:\\Python21\\weave\\ext_tools.py\", line 197, in __init__\n            auto_downcast, type_factories)\n        File \"C:\\Python21\\weave\\ext_tools.py\", line 390, in assign_variable_types\n            raise TypeError, format_error_msg(errors)\n        TypeError: {'buf': \"Unable to convert variable 'buf' to a C++ type.\"}\n    
\n\nThe traceback tells us that inline() was unable to convert 'buf' to a\nC++ type (If instance conversion was implemented, the error would have occurred at \nruntime instead). Why is this? Let's look at what the buf object \nreally is:\n\n
\n    >>> buf\n    pywin.framework.interact.InteractiveView instance at 00EAD014\n    
\n\nPythonWin has reassigned sys.stdout to a special object that \nimplements the Python file interface. This works great in Python, but since \nthe special object doesn't have a FILE* pointer underlying it, fprintf doesn't \nknow what to do with it (well this will be the problem when instance conversion \nis implemented...).\n\n\n

Callable, Instance, and Module Conversion

\n\nNote: Need to look into how ref counts should be handled. Also,\nInstance and Module conversion are not currently implemented.\n\n\n
\n    >>> def a(): \n        pass\n    >>> inline(\"\",['a'])\n    
\n\nCallable and instance variables are converted to PyObject*. Nothing is done\nto there reference counts.\n\n
\n    /* argument conversion code */\n    PyObject* a = py_to_callable(get_variable(\"a\",raw_locals,raw_globals),\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. The py_to_callable() and\npy_to_instance() don't currently increment the ref count.\n\n
    \n    PyObject* py_to_callable(PyObject* py_obj, char* name)\n    {\n        if (!py_obj || !PyCallable_Check(py_obj))\n            handle_bad_type(py_obj,\"callable\", name);    \n        return py_obj;\n    }\n\n    PyObject* py_to_instance(PyObject* py_obj, char* name)\n    {\n        if (!py_obj || !PyFile_Check(py_obj))\n            handle_bad_type(py_obj,\"instance\", name);    \n        return py_obj;\n    }\n    
\n \nThere is no cleanup code for callables, modules, or instances.\n\n\n

Customizing Conversions

\n

\nConverting from Python to C++ types is handled by xxx_specification classes. A \ntype specification class actually serve in two related but different \nroles. The first is in determining whether a Python variable that needs to be \nconverted should be represented by the given class. The second is as a code \ngenerator that generate C++ code needed to convert from Python to C++ types for \na specific variable.\n

\nWhen \n\n

\n    >>> a = 1\n    >>> weave.inline('printf(\"%d\",a);',['a'])\n    
\n \nis called for the first time, the code snippet has to be compiled. In this \nprocess, the variable 'a' is tested against a list of type specifications (the \ndefault list is stored in weave/ext_tools.py). The first \nspecification in the list is used to represent the variable. \n\n

\nExamples of xxx_specification are scattered throughout numerous \n\"xxx_spec.py\" files in the weave package. Closely related to \nthe xxx_specification classes are yyy_info classes. \nThese classes contain compiler, header, and support code information necessary \nfor including a certain set of capabilities (such as blitz++ or CXX support)\nin a compiled module. xxx_specification classes have one or more\nyyy_info classes associated with them.\n\nIf you'd like to define your own set of type specifications, the current best route\nis to examine some of the existing spec and info files. Maybe looking over\nsequence_spec.py and cxx_info.py are a good place to start. After defining \nspecification classes, you'll need to pass them into inline using the \ntype_factories argument. \n\nA lot of times you may just want to change how a specific variable type is \nrepresented. Say you'd rather have Python strings converted to \nstd::string or maybe char* instead of using the CXX \nstring object, but would like all other type conversions to have default \nbehavior. This requires that a new specification class that handles strings\nis written and then prepended to a list of the default type specifications. Since\nit is closer to the front of the list, it effectively overrides the default\nstring specification.\n\nThe following code demonstrates how this is done:\n\n...\n\n\n

The Catalog

\n

\ncatalog.py has a class called catalog that helps keep \ntrack of previously compiled functions. This prevents inline() \nand related functions from having to compile functions everytime they are \ncalled. Instead, catalog will check an in memory cache to see if the function \nhas already been loaded into python. If it hasn't, then it starts searching \nthrough persisent catalogs on disk to see if it finds an entry for the given \nfunction. By saving information about compiled functions to disk, it isn't\nnecessary to re-compile functions everytime you stop and restart the interpreter.\nFunctions are compiled once and stored for future use.\n\n

\nWhen inline(cpp_code) is called the following things happen:\n

    \n
  1. \n A fast local cache of functions is checked for the last function called for \n cpp_code. If an entry for cpp_code doesn't exist in the \n cache or the cached function call fails (perhaps because the function doesn't \n have compatible types) then the next step is to check the catalog. \n
  2. \n The catalog class also keeps an in-memory cache with a list of all the \n functions compiled for cpp_code. If cpp_code has\n ever been called, then this cache will be present (loaded from disk). If\n the cache isn't present, then it is loaded from disk.\n

    \n If the cache is present, each function in the cache is \n called until one is found that was compiled for the correct argument types. If \n none of the functions work, a new function is compiled with the given argument \n types. This function is written to the on-disk catalog as well as into the \n in-memory cache.

    \n
  3. \n When a lookup for cpp_code fails, the catalog looks through \n the on-disk function catalogs for the entries. The PYTHONCOMPILED variable \n determines where to search for these catalogs and in what order. If \n PYTHONCOMPILED is not present several platform dependent locations are \n searched. All functions found for cpp_code in the path are \n loaded into the in-memory cache with functions found earlier in the search \n path closer to the front of the call list.\n

    \n If the function isn't found in the on-disk catalog, \n then the function is compiled, written to the first writable directory in the \n PYTHONCOMPILED path, and also loaded into the in-memory cache.

    \n
  4. \n
\n\n\n

Function Storage: How functions are stored in caches and on disk

\n

\nFunction caches are stored as dictionaries where the key is the entire C++\ncode string and the value is either a single function (as in the \"level 1\"\ncache) or a list of functions (as in the main catalog cache). On disk\ncatalogs are stored in the same manor using standard Python shelves.\n

\nEarly on, there was a question as to whether md5 check sums of the C++\ncode strings should be used instead of the actual code strings. I think this\nis the route inline Perl took. Some (admittedly quick) tests of the md5 vs.\nthe entire string showed that using the entire string was at least a\nfactor of 3 or 4 faster for Python. I think this is because it is more\ntime consuming to compute the md5 value than it is to do look-ups of long\nstrings in the dictionary. Look at the examples/md5_speed.py file for the\ntest run. \n\n\n

Catalog search paths and the PYTHONCOMPILED variable

\n

\nThe default location for catalog files on Unix is is ~/.pythonXX_compiled where \nXX is version of Python being used. If this directory doesn't exist, it is \ncreated the first time a catalog is used. The directory must be writable. If, \nfor any reason it isn't, then the catalog attempts to create a directory based \non your user id in the /tmp directory. The directory permissions are set so \nthat only you have access to the directory. If this fails, I think you're out of \nluck. I don't think either of these should ever fail though. On Windows, a \ndirectory called pythonXX_compiled is created in the user's temporary \ndirectory. \n

\nThe actual catalog file that lives in this directory is a Python shelve with\na platform specific name such as \"nt21compiled_catalog\" so that multiple OSes\ncan share the same file systems without trampling on each other. Along with\nthe catalog file, the .cpp and .so or .pyd files created by inline will live\nin this directory. The catalog file simply contains keys which are the C++\ncode strings with values that are lists of functions. The function lists point\nat functions within these compiled modules. Each function in the lists \nexecutes the same C++ code string, but compiled for different input variables.\n

\nYou can use the PYTHONCOMPILED environment variable to specify alternative\nlocations for compiled functions. On Unix this is a colon (':') separated\nlist of directories. On windows, it is a (';') separated list of directories.\nThese directories will be searched prior to the default directory for a\ncompiled function catalog. Also, the first writable directory in the list\nis where all new compiled function catalogs, .cpp and .so or .pyd files are\nwritten. Relative directory paths ('.' and '..') should work fine in the\nPYTHONCOMPILED variable as should environement variables.\n

\nThere is a \"special\" path variable called MODULE that can be placed in the \nPYTHONCOMPILED variable. It specifies that the compiled catalog should\nreside in the same directory as the module that called it. This is useful\nif an admin wants to build a lot of compiled functions during the build\nof a package and then install them in site-packages along with the package.\nUser's who specify MODULE in their PYTHONCOMPILED variable will have access\nto these compiled functions. Note, however, that if they call the function\nwith a set of argument types that it hasn't previously been built for, the\nnew function will be stored in their default directory (or some other writable\ndirectory in the PYTHONCOMPILED path) because the user will not have write\naccess to the site-packages directory.\n

\nAn example of using the PYTHONCOMPILED path on bash follows:\n\n

\n    PYTHONCOMPILED=MODULE:/some/path;export PYTHONCOMPILED;\n    
\n\nIf you are using python21 on linux, and the module bob.py in site-packages\nhas a compiled function in it, then the catalog search order when calling that\nfunction for the first time in a python session would be:\n\n
\n    /usr/lib/python21/site-packages/linuxpython_compiled\n    /some/path/linuxpython_compiled\n    ~/.python21_compiled/linuxpython_compiled\n    
\n\nThe default location is always included in the search path.\n

\n \nNote: hmmm. see a possible problem here. I should probably make a sub-\ndirectory such as /usr/lib/python21/site-\npackages/python21_compiled/linuxpython_compiled so that library files compiled \nwith python21 are tried to link with python22 files in some strange scenarios. \nNeed to check this.\n\n\n

\nThe in-module cache (in weave.inline_tools reduces the overhead \nof calling inline functions by about a factor of 2. It can be reduced a little \nmore for type loop calls where the same function is called over and over again \nif the cache was a single value instead of a dictionary, but the benefit is \nvery small (less than 5%) and the utility is quite a bit less. So, we'll stick \nwith a dictionary as the cache.\n

\n\n\n

Blitz

\n Note: most of this section is lifted from old documentation. It should be\npretty accurate, but there may be a few discrepancies.\n

\nweave.blitz() compiles Numeric Python expressions for fast \nexecution. For most applications, compiled expressions should provide a \nfactor of 2-10 speed-up over Numeric arrays. Using compiled \nexpressions is meant to be as unobtrusive as possible and works much like \npythons exec statement. As an example, the following code fragment takes a 5 \npoint average of the 512x512 2d image, b, and stores it in array, a:\n\n

\n    from scipy import *  # or from Numeric import *\n    a = ones((512,512), Float64) \n    b = ones((512,512), Float64) \n    # ...do some stuff to fill in b...\n    # now average\n    a[1:-1,1:-1] =  (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] \\\n                   + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n    
\n \nTo compile the expression, convert the expression to a string by putting\nquotes around it and then use weave.blitz:\n\n
\n    import weave\n    expr = \"a[1:-1,1:-1] =  (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n                          \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n    weave.blitz(expr)\n    
\n\nThe first time weave.blitz is run for a given expression and \nset of arguements, C++ code that accomplishes the exact same task as the Python \nexpression is generated and compiled to an extension module. This can take up \nto a couple of minutes depending on the complexity of the function. Subsequent \ncalls to the function are very fast. Futher, the generated module is saved \nbetween program executions so that the compilation is only done once for a \ngiven expression and associated set of array types. If the given expression\nis executed with a new set of array types, the code most be compiled again. This\ndoes not overwrite the previously compiled function -- both of them are saved and\navailable for exectution. \n

\nThe following table compares the run times for standard Numeric code and \ncompiled code for the 5 point averaging.\n

\n

\n\n\n\n\n\n
Method Run Time (seconds)
Standard Numeric 0.46349
blitz (1st time compiling) 78.95526
blitz (subsequent calls) 0.05843 (factor of 8 speedup)
\n
\n

\nThese numbers are for a 512x512 double precision image run on a 400 MHz Celeron \nprocessor under RedHat Linux 6.2.\n

\nBecause of the slow compile times, its probably most effective to develop \nalgorithms as you usually do using the capabilities of scipy or the Numeric \nmodule. Once the algorithm is perfected, put quotes around it and execute it \nusing weave.blitz. This provides the standard rapid \nprototyping strengths of Python and results in algorithms that run close to \nthat of hand coded C or Fortran.\n\n\n

Requirements

\n\nCurrently, the weave.blitz has only been tested under Linux \nwith gcc-2.95-3 and on Windows with Mingw32 (2.95.2). Its compiler \nrequirements are pretty heavy duty (see the \nblitz++ home page), so it won't \nwork with just any compiler. Particularly MSVC++ isn't up to snuff. A number \nof other compilers such as KAI++ will also work, but my suspicions are that gcc \nwill get the most use.\n\n\n

Limitations

\n
    \n
  1. \nCurrently, weave.blitz handles all standard mathematic \noperators except for the ** power operator. The built-in trigonmetric, log, \nfloor/ceil, and fabs functions might work (but haven't been tested). It also \nhandles all types of array indexing supported by the Numeric module. \n

    \nweave.blitz does not currently support operations that use \narray broadcasting, nor have any of the special purpose functions in Numeric \nsuch as take, compress, etc. been implemented. Note that there are no obvious \nreasons why most of this functionality cannot be added to scipy.weave, so it \nwill likely trickle into future versions. Using slice() objects \ndirectly instead of start:stop:step is also not supported.\n

  2. \n
  3. \nCurrently Python only works on expressions that include assignment such as\n \n
    \n    >>> result = b + c + d\n    
    \n\nThis means that the result array must exist before calling \nweave.blitz. Future versions will allow the following:\n\n
    \n    >>> result = weave.blitz_eval(\"b + c + d\")\n    
    \n
  4. \n
  5. \nweave.blitz works best when algorithms can be expressed in a \n\"vectorized\" form. Algorithms that have a large number of if/thens and other \nconditions are better hand written in C or Fortran. Further, the restrictions \nimposed by requiring vectorized expressions sometimes preclude the use of more \nefficient data structures or algorithms. For maximum speed in these cases, \nhand-coded C or Fortran code is the only way to go.\n
  6. \n
  7. \nweave.blitz can produce different results than Numeric in certain \nsituations. It can happen when the array receiving the results of a \ncalculation is also used during the calculation. The Numeric behavior is to \ncarry out the entire calculation on the right hand side of an equation and \nstore it in a temporary array. This temprorary array is assigned to the array \non the left hand side of the equation. blitz, on the other hand, does a \n\"running\" calculation of the array elements assigning values from the right hand\nside to the elements on the left hand side immediately after they are calculated.\nHere is an example, provided by Prabhu Ramachandran, where this happens:\n\n
    \n        # 4 point average.\n        >>> expr = \"u[1:-1, 1:-1] = (u[0:-2, 1:-1] + u[2:, 1:-1] + \"\\\n        ...                \"u[1:-1,0:-2] + u[1:-1, 2:])*0.25\"\n        >>> u = zeros((5, 5), 'd'); u[0,:] = 100\n        >>> exec (expr)\n        >>> u\n        array([[ 100.,  100.,  100.,  100.,  100.],\n               [   0.,   25.,   25.,   25.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.]])\n        \n        >>> u = zeros((5, 5), 'd'); u[0,:] = 100\n        >>> weave.blitz (expr)\n        >>> u\n        array([[ 100.  ,  100.       ,  100.       ,  100.       ,  100. ],\n               [   0.  ,   25.       ,   31.25     ,   32.8125   ,    0. ],\n               [   0.  ,    6.25     ,    9.375    ,   10.546875 ,    0. ],\n               [   0.  ,    1.5625   ,    2.734375 ,    3.3203125,    0. ],\n               [   0.  ,    0.       ,    0.       ,    0.       ,    0. ]])    \n        
    \n \n You can prevent this behavior by using a temporary array.\n \n
    \n        >>> u = zeros((5, 5), 'd'); u[0,:] = 100\n        >>> temp = zeros((4, 4), 'd');\n        >>> expr = \"temp = (u[0:-2, 1:-1] + u[2:, 1:-1] + \"\\\n        ...        \"u[1:-1,0:-2] + u[1:-1, 2:])*0.25;\"\\\n        ...        \"u[1:-1,1:-1] = temp\"\n        >>> weave.blitz (expr)\n        >>> u\n        array([[ 100.,  100.,  100.,  100.,  100.],\n               [   0.,   25.,   25.,   25.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.]])\n        
    \n \n
  8. \n
  9. \nOne other point deserves mention lest people be confused. \nweave.blitz is not a general purpose Python->C compiler. It \nonly works for expressions that contain Numeric arrays and/or \nPython scalar values. This focused scope concentrates effort on the \ncompuationally intensive regions of the program and sidesteps the difficult \nissues associated with a general purpose Python->C compiler.\n
  10. \n
\n\n\n

Numeric efficiency issues: What compilation buys you

\n\nSome might wonder why compiling Numeric expressions to C++ is beneficial since \noperations on Numeric array operations are already executed within C loops. \nThe problem is that anything other than the simplest expression are executed in \nless than optimal fashion. Consider the following Numeric expression:\n\n
\n    a = 1.2 * b + c * d\n    
\n \nWhen Numeric calculates the value for the 2d array, a, it does \nthe following steps:\n\n
\n    temp1 = 1.2 * b\n    temp2 = c * d\n    a = temp1 + temp2\n    
\n \nTwo things to note. Since c is an (perhaps large) array, a large \ntemporary array must be created to store the results of 1.2 * b. \nThe same is true for temp2. Allocation is slow. The second thing \nis that we have 3 loops executing, one to calculate temp1, one for \ntemp2 and one for adding them up. A C loop for the same problem \nmight look like:\n\n
\n    for(int i = 0; i < M; i++)\n        for(int j = 0; j < N; j++)\n            a[i,j] = 1.2 * b[i,j] + c[i,j] * d[i,j]\n    
\n \nHere, the 3 loops have been fused into a single loop and there is no longer\na need for a temporary array. This provides a significant speed improvement\nover the above example (write me and tell me what you get). \n

\nSo, converting Numeric expressions into C/C++ loops that fuse the loops and \neliminate temporary arrays can provide big gains. The goal then,is to convert \nNumeric expression to C/C++ loops, compile them in an extension module, and \nthen call the compiled extension function. The good news is that there is an \nobvious correspondence between the Numeric expression above and the C loop. The \nbad news is that Numeric is generally much more powerful than this simple \nexample illustrates and handling all possible indexing possibilities results in \nloops that are less than straight forward to write. (take a peak in Numeric for \nconfirmation). Luckily, there are several available tools that simplify the \nprocess.\n\n\n

The Tools

\n\nweave.blitz relies heavily on several remarkable tools. On the \nPython side, the main facilitators are Jermey Hylton's parser module and Jim \nHuginin's Numeric module. On the compiled language side, Todd Veldhuizen's \nblitz++ array library, written in C++ (shhhh. don't tell David Beazley), does \nthe heavy lifting. Don't assume that, because it's C++, it's much slower than C \nor Fortran. Blitz++ uses a jaw dropping array of template techniques \n(metaprogramming, template expression, etc) to convert innocent looking and \nreadable C++ expressions into to code that usually executes within a few \npercentage points of Fortran code for the same problem. This is good. \nUnfortunately all the template raz-ma-taz is very expensive to compile, so the \n200 line extension modules often take 2 or more minutes to compile. This isn't so \ngood. weave.blitz works to minimize this issue by remembering \nwhere compiled modules live and reusing them instead of re-compiling every time \na program is re-run.\n\n\n

Parser

\nTearing Numeric expressions apart, examining the pieces, and then rebuilding \nthem as C++ (blitz) expressions requires a parser of some sort. I can imagine \nsomeone attacking this problem with regular expressions, but it'd likely be \nugly and fragile. Amazingly, Python solves this problem for us. It actually \nexposes its parsing engine to the world through the parser module. \nThe following fragment creates an Abstract Syntax Tree (AST) object for the \nexpression and then converts to a (rather unpleasant looking) deeply nested list \nrepresentation of the tree. \n \n
\n    >>> import parser\n    >>> import scipy.weave.misc\n    >>> ast = parser.suite(\"a = b * c + d\")\n    >>> ast_list = ast.tolist()\n    >>> sym_list = scipy.weave.misc.translate_symbols(ast_list)\n    >>> pprint.pprint(sym_list)\n    ['file_input',\n     ['stmt',\n      ['simple_stmt',\n       ['small_stmt',\n        ['expr_stmt',\n         ['testlist',\n          ['test',\n           ['and_test',\n            ['not_test',\n             ['comparison',\n              ['expr',\n               ['xor_expr',\n                ['and_expr',\n                 ['shift_expr',\n                  ['arith_expr',\n                   ['term',\n                    ['factor', ['power', ['atom', ['NAME', 'a']]]]]]]]]]]]]]],\n         ['EQUAL', '='],\n         ['testlist',\n          ['test',\n           ['and_test',\n            ['not_test',\n             ['comparison',\n              ['expr',\n               ['xor_expr',\n                ['and_expr',\n                 ['shift_expr',\n                  ['arith_expr',\n                   ['term',\n                    ['factor', ['power', ['atom', ['NAME', 'b']]]],\n                    ['STAR', '*'],\n                    ['factor', ['power', ['atom', ['NAME', 'c']]]]],\n                   ['PLUS', '+'],\n                   ['term',\n                    ['factor', ['power', ['atom', ['NAME', 'd']]]]]]]]]]]]]]]]],\n       ['NEWLINE', '']]],\n     ['ENDMARKER', '']]\n    
\n\nDespite its looks, with some tools developed by Jermey H., its possible\nto search these trees for specific patterns (sub-trees), extract the \nsub-tree, manipulate them converting python specific code fragments\nto blitz code fragments, and then re-insert it in the parse tree. The parser\nmodule documentation has some details on how to do this. Traversing the \nnew blitzified tree, writing out the terminal symbols as you go, creates\nour new blitz++ expression string.\n\n \n

Blitz and Numeric

\nThe other nice discovery in the project is that the data structure used\nfor Numeric arrays and blitz arrays is nearly identical. Numeric stores\n\"strides\" as byte offsets and blitz stores them as element offsets, but\nother than that, they are the same. Further, most of the concept and\ncapabilities of the two libraries are remarkably similar. It is satisfying \nthat two completely different implementations solved the problem with \nsimilar basic architectures. It is also fortitous. The work involved in \nconverting Numeric expressions to blitz expressions was greatly diminished.\nAs an example, consider the code for slicing an array in Python with a\nstride:\n\n
\n    >>> a = b[0:4:2] + c\n    >>> a\n    [0,2,4]\n    
\n\n\nIn Blitz it is as follows:\n\n
\n    Array<2,int> b(10);\n    Array<2,int> c(3);\n    // ...\n    Array<2,int> a = b(Range(0,3,2)) + c;\n    
\n\n\nHere the range object works exactly like Python slice objects with the exception\nthat the top index (3) is inclusive where as Python's (4) is exclusive. Other \ndifferences include the type declaraions in C++ and parentheses instead of \nbrackets for indexing arrays. Currently, weave.blitz handles the \ninclusive/exclusive issue by subtracting one from upper indices during the\ntranslation. An alternative that is likely more robust/maintainable in the \nlong run, is to write a PyRange class that behaves like Python's range. \nThis is likely very easy.\n

\nThe stock blitz also doesn't handle negative indices in ranges. The current \nimplementation of the blitz() has a partial solution to this \nproblem. It calculates and index that starts with a '-' sign by subtracting it \nfrom the maximum index in the array so that:\n\n

\n                    upper index limit\n                        /-----\\\n    b[:-1] -> b(Range(0,Nb[0]-1-1))\n    
\n\nThis approach fails, however, when the top index is calculated from other \nvalues. In the following scenario, if i+j evaluates to a negative \nvalue, the compiled code will produce incorrect results and could even core-\ndump. Right now, all calculated indices are assumed to be positive.\n \n
\n    b[:i-j] -> b(Range(0,i+j))\n    
\n\nA solution is to calculate all indices up front using if/then to handle the\n+/- cases. This is a little work and results in more code, so it hasn't been\ndone. I'm holding out to see if blitz++ can be modified to handle negative\nindexing, but haven't looked into how much effort is involved yet. While it \nneeds fixin', I don't think there is a ton of code where this is an issue.\n

\nThe actual translation of the Python expressions to blitz expressions is \ncurrently a two part process. First, all x:y:z slicing expression are removed\nfrom the AST, converted to slice(x,y,z) and re-inserted into the tree. Any\nmath needed on these expressions (subtracting from the \nmaximum index, etc.) are also preformed here. _beg and _end are used as special\nvariables that are defined as blitz::fromBegin and blitz::toEnd.\n\n

\n    a[i+j:i+j+1,:] = b[2:3,:] \n    
\n\nbecomes a more verbose:\n \n
\n    a[slice(i+j,i+j+1),slice(_beg,_end)] = b[slice(2,3),slice(_beg,_end)]\n    
\n \nThe second part does a simple string search/replace to convert to a blitz \nexpression with the following translations:\n\n
\n    slice(_beg,_end) -> _all  # not strictly needed, but cuts down on code.\n    slice            -> blitz::Range\n    [                -> (\n    ]                -> )\n    _stp             -> 1\n    
\n\n_all is defined in the compiled function as \nblitz::Range.all(). These translations could of course happen \ndirectly in the syntax tree. But the string replacement is slightly easier. \nNote that name spaces are maintained in the C++ code to lessen the likelyhood \nof name clashes. Currently no effort is made to detect name clashes. A good \nrule of thumb is don't use values that start with '_' or 'py_' in compiled \nexpressions and you'll be fine.\n\n \n

Type definitions and coersion

\n\nSo far we've glossed over the dynamic vs. static typing issue between Python \nand C++. In Python, the type of value that a variable holds can change\nthrough the course of program execution. C/C++, on the other hand, forces you\nto declare the type of value a variables will hold prior at compile time.\nweave.blitz handles this issue by examining the types of the\nvariables in the expression being executed, and compiling a function for those\nexplicit types. For example:\n\n
\n    a = ones((5,5),Float32)\n    b = ones((5,5),Float32)\n    weave.blitz(\"a = a + b\")\n    
\n\nWhen compiling this expression to C++, weave.blitz sees that the\nvalues for a and b in the local scope have type Float32, or 'float'\non a 32 bit architecture. As a result, it compiles the function using \nthe float type (no attempt has been made to deal with 64 bit issues).\nIt also goes one step further. If all arrays have the same type, a templated\nversion of the function is made and instantiated for float, double, \ncomplex, and complex arrays. Note: This feature has been \nremoved from the current version of the code. Each version will be compiled\nseparately \n

\nWhat happens if you call a compiled function with array types that are \ndifferent than the ones for which it was originally compiled? No biggie, you'll \njust have to wait on it to compile a new version for your new types. This \ndoesn't overwrite the old functions, as they are still accessible. See the \ncatalog section in the inline() documentation to see how this is handled. \nSuffice to say, the mechanism is transparent to the user and behaves \nlike dynamic typing with the occasional wait for compiling newly typed \nfunctions.\n

\nWhen working with combined scalar/array operations, the type of the array is \nalways used. This is similar to the savespace flag that was recently \nadded to Numeric. This prevents issues with the following expression perhaps \nunexpectedly being calculated at a higher (more expensive) precision that can \noccur in Python:\n\n

\n    >>> a = array((1,2,3),typecode = Float32)\n    >>> b = a * 2.1 # results in b being a Float64 array.\n    
\n \nIn this example, \n\n
\n    >>> a = ones((5,5),Float32)\n    >>> b = ones((5,5),Float32)\n    >>> weave.blitz(\"b = a * 2.1\")\n    
\n \nthe 2.1 is cast down to a float before carrying out \nthe operation. If you really want to force the calculation to be a \ndouble, define a and b as \ndouble arrays.\n

\nOne other point of note. Currently, you must include both the right hand side \nand left hand side (assignment side) of your equation in the compiled \nexpression. Also, the array being assigned to must be created prior to calling \nweave.blitz. I'm pretty sure this is easily changed so that a \ncompiled_eval expression can be defined, but no effort has been made to \nallocate new arrays (and decern their type) on the fly.\n\n \n

Cataloging Compiled Functions

\n\nSee the Cataloging functions section in the \nweave.inline() documentation.\n\n \n

Checking Array Sizes

\n\nSurprisingly, one of the big initial problems with compiled code was making\nsure all the arrays in an operation were of compatible type. The following\ncase is trivially easy:\n\n
\n    a = b + c\n    
\n \nIt only requires that arrays a, b, and c \nhave the same shape. However, expressions like:\n\n
\n    a[i+j:i+j+1,:] = b[2:3,:] + c\n    
\n\nare not so trivial. Since slicing is involved, the size of the slices, not the \ninput arrays must be checked. Broadcasting complicates things further because \narrays and slices with different dimensions and shapes may be compatible for \nmath operations (broadcasting isn't yet supported by \nweave.blitz). Reductions have a similar effect as their \nresults are different shapes than their input operand. The binary operators in \nNumeric compare the shapes of their two operands just before they operate on \nthem. This is possible because Numeric treats each operation independently. \nThe intermediate (temporary) arrays created during sub-operations in an \nexpression are tested for the correct shape before they are combined by another \noperation. Because weave.blitz fuses all operations into a \nsingle loop, this isn't possible. The shape comparisons must be done and \nguaranteed compatible before evaluating the expression.\n

\nThe solution chosen converts input arrays to \"dummy arrays\" that only represent \nthe dimensions of the arrays, not the data. Binary operations on dummy arrays \ncheck that input array sizes are comptible and return a dummy array with the \nsize correct size. Evaluating an expression of dummy arrays traces the \nchanging array sizes through all operations and fails if incompatible array \nsizes are ever found. \n

\nThe machinery for this is housed in weave.size_check. It \nbasically involves writing a new class (dummy array) and overloading it math \noperators to calculate the new sizes correctly. All the code is in Python and \nthere is a fair amount of logic (mainly to handle indexing and slicing) so the \noperation does impose some overhead. For large arrays (ie. 50x50x50), the \noverhead is negligible compared to evaluating the actual expression. For small \narrays (ie. 16x16), the overhead imposed for checking the shapes with this \nmethod can cause the weave.blitz to be slower than evaluating \nthe expression in Python. \n

\nWhat can be done to reduce the overhead? (1) The size checking code could be \nmoved into C. This would likely remove most of the overhead penalty compared \nto Numeric (although there is also some calling overhead), but no effort has \nbeen made to do this. (2) You can also call weave.blitz with\ncheck_size=0 and the size checking isn't done. However, if the \nsizes aren't compatible, it can cause a core-dump. So, foregoing size_checking\nisn't advisable until your code is well debugged.\n\n \n

Creating the Extension Module

\n\nweave.blitz uses the same machinery as \nweave.inline to build the extension module. The only difference\nis the code included in the function is automatically generated from the\nNumeric array expression instead of supplied by the user.\n\n\n

Extension Modules

\nweave.inline and weave.blitz are high level tools\nthat generate extension modules automatically. Under the covers, they use several\nclasses from weave.ext_tools to help generate the extension module.\nThe main two classes are ext_module and ext_function (I'd\nlike to add ext_class and ext_method also). These classes\nsimplify the process of generating extension modules by handling most of the \"boiler\nplate\" code automatically.\n\n\nNote: inline actually sub-classes weave.ext_tools.ext_function \nto generate slightly different code than the standard ext_function.\nThe main difference is that the standard class converts function arguments to\nC types, while inline always has two arguments, the local and global dicts, and\nthe grabs the variables that need to be convereted to C from these.\n\n\n\n

A Simple Example

\nThe following simple example demonstrates how to build an extension module within\na Python function:\n\n
\n    # examples/increment_example.py\n    from weave import ext_tools\n    \n    def build_increment_ext():\n        \"\"\" Build a simple extension with functions that increment numbers.\n            The extension will be built in the local directory.\n        \"\"\"        \n        mod = ext_tools.ext_module('increment_ext')\n    \n        a = 1 # effectively a type declaration for 'a' in the \n              # following functions.\n    \n        ext_code = \"return_val = Py::new_reference_to(Py::Int(a+1));\"    \n        func = ext_tools.ext_function('increment',ext_code,['a'])\n        mod.add_function(func)\n        \n        ext_code = \"return_val = Py::new_reference_to(Py::Int(a+2));\"    \n        func = ext_tools.ext_function('increment_by_2',ext_code,['a'])\n        mod.add_function(func)\n                \n        mod.compile()\n    
\n\n\nThe function build_increment_ext() creates an extension module \nnamed increment_ext and compiles it to a shared library (.so or \n.pyd) that can be loaded into Python.. increment_ext contains two \nfunctions, increment and increment_by_2. \n\nThe first line of build_increment_ext(),\n\n
\n        mod = ext_tools.ext_module('increment_ext') \n    
\n\ncreates an ext_module instance that is ready to have \next_function instances added to it. ext_function \ninstances are created much with a calling convention similar to \nweave.inline(). The most common call includes a C/C++ code \nsnippet and a list of the arguments for the function. The following\n\n
\n        ext_code = \"return_val = Py::new_reference_to(Py::Int(a+1));\"    \n        func = ext_tools.ext_function('increment',ext_code,['a'])\n    
\n \ncreates a C/C++ extension function that is equivalent to the following Python\nfunction:\n\n
\n        def increment(a):\n            return a + 1\n    
\n\nA second method is also added to the module and then,\n\n
\n        mod.compile()\n    
\n\nis called to build the extension module. By default, the module is created\nin the current working directory.\n\nThis example is available in the examples/increment_example.py file\nfound in the weave directory. At the bottom of the file in the\nmodule's \"main\" program, an attempt to import increment_ext without\nbuilding it is made. If this fails (the module doesn't exist in the PYTHONPATH), \nthe module is built by calling build_increment_ext(). This approach\nonly takes the time consuming ( a few seconds for this example) process of building\nthe module if it hasn't been built before.\n\n
\n    if __name__ == \"__main__\":\n        try:\n            import increment_ext\n        except ImportError:\n            build_increment_ext()\n            import increment_ext\n        a = 1\n        print 'a, a+1:', a, increment_ext.increment(a)\n        print 'a, a+2:', a, increment_ext.increment_by_2(a)           \n    
\n\n\nNote: If we were willing to always pay the penalty of building the C++ code for \na module, we could store the md5 checksum of the C++ code along with some \ninformation about the compiler, platform, etc. Then, \next_module.compile() could try importing the module before it actually\ncompiles it, check the md5 checksum and other meta-data in the imported module\nwith the meta-data of the code it just produced and only compile the code if\nthe module didn't exist or the meta-data didn't match. This would reduce the\nabove code to:\n\n
\n    if __name__ == \"__main__\":\n        build_increment_ext()\n\n        a = 1\n        print 'a, a+1:', a, increment_ext.increment(a)\n        print 'a, a+2:', a, increment_ext.increment_by_2(a)           \n    
\n\nNote: There would always be the overhead of building the C++ code, but it would only actually compile the code once. You pay a little in overhead and get cleaner\n\"import\" code. Needs some thought.\n\n

\n\nIf you run increment_example.py from the command line, you get\nthe following:\n\n

\n    [eric@n0]$ python increment_example.py\n    a, a+1: 1 2\n    a, a+2: 1 3\n    
\n\nIf the module didn't exist before it was run, the module is created. If it did\nexist, it is just imported and used.\n\n\n

Fibonacci Example

\nexamples/fibonacci.py provides a little more complex example of \nhow to use ext_tools. Fibonacci numbers are a series of numbers \nwhere each number in the series is the sum of the previous two: 1, 1, 2, 3, 5, \n8, etc. Here, the first two numbers in the series are taken to be 1. One \napproach to calculating Fibonacci numbers uses recursive function calls. In \nPython, it might be written as:\n\n
\n    def fib(a):\n        if a <= 2:\n            return 1\n        else:\n            return fib(a-2) + fib(a-1)\n    
\n\nIn C, the same function would look something like this:\n\n
\n     int fib(int a)\n     {                   \n         if(a <= 2)\n             return 1;\n         else\n             return fib(a-2) + fib(a-1);  \n     }                      \n    
\n\nRecursion is much faster in C than in Python, so it would be beneficial\nto use the C version for fibonacci number calculations instead of the\nPython version. We need an extension function that calls this C function\nto do this. This is possible by including the above code snippet as \n\"support code\" and then calling it from the extension function. Support \ncode snippets (usually structure definitions, helper functions and the like)\nare inserted into the extension module C/C++ file before the extension\nfunction code. Here is how to build the C version of the fibonacci number\ngenerator:\n\n
\ndef build_fibonacci():\n    \"\"\" Builds an extension module with fibonacci calculators.\n    \"\"\"\n    mod = ext_tools.ext_module('fibonacci_ext')\n    a = 1 # this is effectively a type declaration\n    \n    # recursive fibonacci in C \n    fib_code = \"\"\"\n                   int fib1(int a)\n                   {                   \n                       if(a <= 2)\n                           return 1;\n                       else\n                           return fib1(a-2) + fib1(a-1);  \n                   }                         \n               \"\"\"\n    ext_code = \"\"\"\n                   int val = fib1(a);\n                   return_val = Py::new_reference_to(Py::Int(val));\n               \"\"\"    \n    fib = ext_tools.ext_function('fib',ext_code,['a'])\n    fib.customize.add_support_code(fib_code)\n    mod.add_function(fib)\n\n    mod.compile()\n\n    
\n\nXXX More about custom_info, and what xxx_info instances are good for.\n\n

\n\nNote: recursion is not the fastest way to calculate fibonacci numbers, but this \napproach serves nicely for this example.\n\n

\n\n

Customizing Type Conversions -- Type Factories

\nnot written\n\n

Things I wish weave did

\n\nIt is possible to get name clashes if you uses a variable name that is already defined\nin a header automatically included (such as stdio.h) For instance, if you\ntry to pass in a variable named stdout, you'll get a cryptic error report\ndue to the fact that stdio.h also defines the name. weave\nshould probably try and handle this in some way.\n\nOther things...", "source_code_before": "\n

Weave Documentation

\n

\nBy Eric Jones eric@enthought.com\n

\n

Outline

\n
\n
Introduction\n
Requirements\n
Installation\n
Testing\n
Benchmarks\n
Inline\n
\n
More with printf\n
\n More examples\n
\n
Binary search\n
Dictionary sort\n
Numeric -- cast/copy/transpose\n
wxPython
\n
\n
Keyword options\n
Returning values\n
\n
\n The issue with locals()
\n
\n
A quick look at the code\n
\n Technical Details\n
\n
Converting Types\n
\n
\n Numeric Argument Conversion\n
\n String, List, Tuple, and Dictionary Conversion\n
File Conversion \n
\n Callable, Instance, and Module Conversion \n
Customizing Conversions\n
\n
Compiling Code\n
\"Cataloging\" functions\n
\n
Function Storage\n
The PYTHONCOMPILED evnironment variable
\n
\n
\n
\n
\n
\n
Blitz\n
\n
Requirements\n
Limitations\n
Numeric Efficiency Issues\n
The Tools \n
\n
Parser\n
Blitz and Numeric\n
\n
Type defintions and coersion\n
Cataloging Compiled Functions\n
Checking Array Sizes\n
Creating the Extension Module\n
\n
Extension Modules\n
\n
A Simple Example\n
Fibonacci Example\n
\n
Customizing Type Conversions -- Type Factories (not written)\n
\n
Type Specifications\n
Type Information\n
The Conversion Process \n
\n
\n\n

Introduction

\n\n

\nThe weave package provides tools for including C/C++ code within\nin Python code. This offers both another level of optimization to those who need \nit, and an easy way to modify and extend any supported extension libraries such \nas wxPython and hopefully VTK soon. Inlining C/C++ code within Python generally\nresults in speed ups of 1.5x to 30x speed-up over algorithms written in pure\nPython (However, it is also possible to slow things down...). Generally \nalgorithms that require a large number of calls to the Python API don't benefit\nas much from the conversion to C/C++ as algorithms that have inner loops \ncompletely convertable to C.\n

\nThere are three basic ways to use weave. The \nweave.inline() function executes C code directly within Python, \nand weave.blitz() translates Python Numeric expressions to C++ \nfor fast execution. blitz() was the original reason \nweave was built. For those interested in building extension\nlibraries, the ext_tools module provides classes for building \nextension modules within Python. \n

\nMost of weave's functionality should work on Windows and Unix, \nalthough some of its functionality requires gcc or a similarly \nmodern C++ compiler that handles templates well. Up to now, most testing has \nbeen done on Windows 2000 with Microsoft's C++ compiler (MSVC) and with gcc \n(mingw32 2.95.2 and 2.95.3-6). All tests also pass on Linux (RH 7.1 \nwith gcc 2.96), and I've had reports that it works on Debian also (thanks \nPearu).\n

\nThe inline and blitz provide new functionality to \nPython (although I've recently learned about the PyInline project which may offer \nsimilar functionality to inline). On the other hand, tools for \nbuilding Python extension modules already exists (SWIG, SIP, pycpp, CXX, and \nothers). As of yet, I'm not sure where weave fits in this \nspectrum. It is closest in flavor to CXX in that it makes creating new C/C++ \nextension modules pretty easy. However, if you're wrapping a gaggle of legacy \nfunctions or classes, SWIG and friends are definitely the better choice. \nweave is set up so that you can customize how Python types are \nconverted to C types in weave. This is great for \ninline(), but, for wrapping legacy code, it is more flexible to \nspecify things the other way around -- that is how C types map to Python types. \nThis weave does not do. I guess it would be possible to build \nsuch a tool on top of weave, but with good tools like SWIG around, \nI'm not sure the effort produces any new capabilities. Things like function \noverloading are probably easily implemented in weave and it might \nbe easier to mix Python/C code in function calls, but nothing beyond this comes \nto mind. So, if you're developing new extension modules or optimizing Python \nfunctions in C, weave.ext_tools() might be the tool \nfor you. If you're wrapping legacy code, stick with SWIG.\n

\nThe next several sections give the basics of how to use weave.\nWe'll discuss what's happening under the covers in more detail later \non. Serious users will need to at least look at the type conversion section to \nunderstand how Python variables map to C/C++ types and how to customize this \nbehavior. One other note. If you don't know C or C++ then these docs are \nprobably of very little help to you. Further, it'd be helpful if you know \nsomething about writing Python extensions. weave does quite a \nbit for you, but for anything complex, you'll need to do some conversions, \nreference counting, etc.\n

\n\nNote: weave is actually part of the SciPy package. However, it works fine as a \nstandalone package. The examples here are given as if it is used as a stand \nalone package. If you are using from within scipy, you can use from \nscipy import weave and the examples will work identically.\n\n\n

Requirements

\n
    \n
  • Python\n

    \n I use 2.1.1. Probably 2.0 or higher should work.\n

    \n

  • \n \n
  • C++ compiler\n

    \n weave uses distutils to actually build \n extension modules, so it uses whatever compiler was originally used to \n build Python. weave itself requires a C++ compiler. If \n you used a C++ compiler to build Python, your probably fine.\n

    \n On Unix gcc is the preferred choice because I've done a little \n testing with it. All testing has been done with gcc, but I expect the \n majority of compilers should work for inline and \n ext_tools. The one issue I'm not sure about is that I've \n hard coded things so that compilations are linked with the \n stdc++ library. Is this standard across \n Unix compilers, or is this a gcc-ism?\n

    \n For blitz(), you'll need a reasonably recent version of \n gcc. 2.95.2 works on windows and 2.96 looks fine on Linux. Other \n versions are likely to work. Its likely that KAI's C++ compiler and \n maybe some others will work, but I haven't tried. My advice is to use \n gcc for now unless your willing to tinker with the code some.\n

    \n On Windows, either MSVC or gcc (www.mingw.org\" > mingw32) should work. Again, \n you'll need gcc for blitz() as the\n MSVC compiler doesn't handle templates well.\n

    \n I have not tried Cygwin, so please report success if it works for you.\n

    \n

  • \n\n
  • Numeric (optional)\n

    \n The python Numeric module from here. is required for \n blitz() to work. Be sure and get NumPy, not NumArray\n which is the \"next generation\" implementation. This is not\n required for using inline() or ext_tools.\n

    \n

  • \n
  • scipy_distutils and scipy_test (packaged with weave)\n

    \n These two modules are packaged with weave in both\n the windows installer and the source distributions. If you are using\n CVS, however, you'll need to download these separately (also available\n through CVS at SciPy).\n

    \n

  • \n
\n

\n\n\n

Installation

\n

\nThere are currently two ways to get weave. Fist, \nweave is part of SciPy and installed automatically (as a sub-\npackage) whenever SciPy is installed (although the latest version isn't in \nSciPy yet, so use this one for now). Second, since weave is \nuseful outside of the scientific community, it has been setup so that it can be\nused as a stand-alone module. \n\n

\nThe stand-alone version can be downloaded from here. Unix users should grab the \ntar ball (.tgz file) and install it using the following commands.\n\n

\n    tar -xzvf weave-0.2.tar.gz\n    cd weave-0.2\n    python setup.py install\n    
\n\nThis will also install two other packages, scipy_distutils and \nscipy_test. The first is needed by the setup process itself and \nboth are used in the unit-testing process. Numeric is required if you want to \nuse blitz(), but isn't necessary for inline() or \next_tools\n

\nFor Windows users, it's even easier. You can download the click-install .exe \nfile and run it for automatic installation. There is also a .zip file of the\nsource for those interested. It also includes a setup.py file to simplify\ninstallation. \n

\nIf you're using the CVS version, you'll need to install \nscipy_distutils and scipy_test packages (also \navailable from CVS) on your own.\n

\n \nNote: The dependency issue here is a little sticky. I hate to make people \ndownload more than one file (and so I haven't), but distutils doesn't have a \nway to do conditional installation -- at least that I know about. This can \nlead to undesired clobbering of the scipy_test and scipy_distutils modules. \nWhat to do, what to do... Right now it is a very minor issue.\n\n

\n\n

Testing

\nOnce weave is installed, fire up python and run its unit tests.\n\n
\n    >>> import weave\n    >>> weave.test()\n    runs long time... spews tons of output and a few warnings\n    .\n    .\n    .\n    ..............................................................\n    ................................................................\n    ..................................................\n    ----------------------------------------------------------------------\n    Ran 184 tests in 158.418s\n\n    OK\n    \n    >>> \n    
\n\nThis takes a loooong time. On windows, it is usually several minutes. On Unix \nwith remote file systems, I've had it take 15 or so minutes. In the end, it \nshould run about 180 tests and spew some speed results along the way. If you \nget errors, they'll be reported at the end of the output. Please let me know\nwhat if this occurs.\n\nIf you don't have Numeric installed, you'll get some module import errors \nduring the test setup phase for modules that are Numeric specific (blitz_spec, \nblitz_tools, size_check, standard_array_spec, ast_tools), but all test should\npass (about 100 and they should complete in several minutes).\n

\nIf you only want to test a single module of the package, you can do this by\nrunning test() for that specific module.\n\n

\n    >>> import weave.scalar_spec\n    >>> weave.scalar_spec.test()\n    .......\n    ----------------------------------------------------------------------\n    Ran 7 tests in 23.284s\n    
\n\nTesting Notes:\n
    \n
  • \n Windows 1\n

    \n I've had some test fail on windows machines where I have msvc, gcc-2.95.2 \n (in c:\\gcc-2.95.2), and gcc-2.95.3-6 (in c:\\gcc) all installed. My \n environment has c:\\gcc in the path and does not have c:\\gcc-2.95.2 in the \n path. The test process runs very smoothly until the end where several test \n using gcc fail with cpp0 not found by g++. If I check os.system('gcc -v') \n before running tests, I get gcc-2.95.3-6. If I check after running tests \n (and after failure), I get gcc-2.95.2. ??huh??. The os.environ['PATH'] \n still has c:\\gcc first in it and is not corrupted (msvc/distutils messes \n with the environment variables, so we have to undo its work in some \n places). If anyone else sees this, let me know - - it may just be an quirk \n on my machine (unlikely). Testing with the gcc- 2.95.2 installation always \n works.\n

    \n

  • \n
  • \n Windows 2\n

    \n If you run the tests from PythonWin or some other GUI tool, you'll get a\n ton of DOS windows popping up periodically as weave spawns\n the compiler multiple times. Very annoying. Anyone know how to fix this?\n

    \n

  • \n
  • \n wxPython\n

    \n wxPython tests are not enabled by default because importing wxPython on a \n Unix machine without access to a X-term will cause the program to exit. \n Anyone know of a safe way to detect whether wxPython can be imported and \n whether a display exists on a machine? \n

    \n

  • \n
    \n\n

    \n

\n\n\n

Benchmarks

\nThis section has a few benchmarks -- thats all people want to see anyway right? \nThese are mostly taken from running files in the weave/example \ndirectory and also from the test scripts. Without more information about what \nthe test actually do, their value is limited. Still, their here for the \ncurious. Look at the example scripts for more specifics about what problem was \nactually solved by each run. These examples are run under windows 2000 using \nMicrosoft Visual C++ and python2.1 on a 850 MHz PIII laptop with 320 MB of RAM.\nSpeed up is the improvement (degredation) factor of weave compared to \nconventional Python functions. The blitz() comparisons are shown\ncompared to Numeric.\n

\n

\n\n\n \n \n \n \n \n \n \n \n\n \n \n \n \n \n \n
\n

inline and ext_tools

Algorithm

Speed up

binary search   1.50
fibonacci (recursive)  82.10
fibonacci (loop)   9.17
return None   0.14
map   1.20
dictionary sort   2.54
vector quantization  37.40
\n

blitz -- double precision

Algorithm

Speed up

a = b + c 512x512   3.05
a = b + c + d 512x512   4.59
5 pt avg. filter, 2D Image 512x512   9.01
Electromagnetics (FDTD) 100x100x100   8.61
\n
\n

\n\nThe benchmarks shown blitz in the best possible light. Numeric \n(at least on my machine) is significantly worse for double precision than it is \nfor single precision calculations. If your interested in single precision \nresults, you can pretty much divide the double precision speed up by 3 and you'll\nbe close.\n\n\n

Inline

\n

\ninline() compiles and executes C/C++ code on the fly. Variables \nin the local and global Python scope are also available in the C/C++ code. \nValues are passed to the C/C++ code by assignment much like variables \nare passed into a standard Python function. Values are returned from the C/C++ \ncode through a special argument called return_val. Also, the contents of \nmutable objects can be changed within the C/C++ code and the changes remain \nafter the C code exits and returns to Python. (more on this later)\n

\nHere's a trivial printf example using inline():\n\n

\n    >>> import weave    \n    >>> a  = 1\n    >>> weave.inline('printf(\"%d\\\\n\",a);',['a'])\n    1\n    
\n

\nIn this, its most basic form, inline(c_code, var_list) requires two \narguments. c_code is a string of valid C/C++ code. \nvar_list is a list of variable names that are passed from \nPython into C/C++. Here we have a simple printf statement that \nwrites the Python variable a to the screen. The first time you run \nthis, there will be a pause while the code is written to a .cpp file, compiled \ninto an extension module, loaded into Python, cataloged for future use, and \nexecuted. On windows (850 MHz PIII), this takes about 1.5 seconds when using \nMicrosoft's C++ compiler (MSVC) and 6-12 seconds using gcc (mingw32 2.95.2). \nAll subsequent executions of the code will happen very quickly because the code \nonly needs to be compiled once. If you kill and restart the interpreter and then \nexecute the same code fragment again, there will be a much shorter delay in the \nfractions of seconds range. This is because weave stores a \ncatalog of all previously compiled functions in an on disk cache. When it sees \na string that has been compiled, it loads the already compiled module and \nexecutes the appropriate function. \n

\n\nNote: If you try the printf example in a GUI shell such as IDLE, \nPythonWin, PyShell, etc., you're unlikely to see the output. This is because the \nC code is writing to stdout, instead of to the GUI window. This doesn't mean \nthat inline doesn't work in these environments -- it only means that standard \nout in C is not the same as the standard out for Python in these cases. Non \ninput/output functions will work as expected.\n\n

\nAlthough effort has been made to reduce the overhead associated with calling \ninline, it is still less efficient for simple code snippets than using \nequivalent Python code. The simple printf example is actually \nslower by 30% or so than using Python print statement. And, it is \nnot difficult to create code fragments that are 8-10 times slower using inline \nthan equivalent Python. However, for more complicated algorithms, \nthe speed up can be worth while -- anywhwere from 1.5- 30 times faster. \nAlgorithms that have to manipulate Python objects (sorting a list) usually only \nsee a factor of 2 or so improvement. Algorithms that are highly computational \nor manipulate Numeric arrays can see much larger improvements. The \nexamples/vq.py file shows a factor of 30 or more improvement on the vector \nquantization algorithm that is used heavily in information theory and \nclassification problems.\n

\n\n\n

More with printf

\n

\nMSVC users will actually see a bit of compiler output that distutils does not\nsupress the first time the code executes:\n\n

    \n    >>> weave.inline(r'printf(\"%d\\n\",a);',['a'])\n    sc_e013937dbc8c647ac62438874e5795131.cpp\n       Creating library C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\n       \\Release\\sc_e013937dbc8c647ac62438874e5795131.lib and object C:\\DOCUME\n       ~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_e013937dbc8c64\n       7ac62438874e5795131.exp\n    1\n    
\n

\nNothing bad is happening, its just a bit annoying. Anyone know how to \nturn this off? \n

\nThis example also demonstrates using 'raw strings'. The r \npreceeding the code string in the last example denotes that this is a 'raw \nstring'. In raw strings, the backslash character is not interpreted as an \nescape character, and so it isn't necessary to use a double backslash to \nindicate that the '\\n' is meant to be interpreted in the C printf \nstatement instead of by Python. If your C code contains a lot\nof strings and control characters, raw strings might make things easier.\nMost of the time, however, standard strings work just as well.\n\n

\nThe printf statement in these examples is formatted to print \nout integers. What happens if a is a string? inline\nwill happily, compile a new version of the code to accept strings as input,\nand execute the code. The result?\n\n

    \n    >>> a = 'string'\n    >>> weave.inline(r'printf(\"%d\\n\",a);',['a'])\n    32956972\n    
\n

\nIn this case, the result is non-sensical, but also non-fatal. In other \nsituations, it might produce a compile time error because a is \nrequired to be an integer at some point in the code, or it could produce a \nsegmentation fault. Its possible to protect against passing \ninline arguments of the wrong data type by using asserts in \nPython.\n\n

    \n    >>> a = 'string'\n    >>> def protected_printf(a):    \n    ...     assert(type(a) == type(1))\n    ...     weave.inline(r'printf(\"%d\\n\",a);',['a'])\n    >>> protected_printf(1)\n     1\n    >>> protected_printf('string')\n    AssertError...\n    
\n\n

\nFor printing strings, the format statement needs to be changed.\n\n

    \n    >>> a = 'string'\n    >>> weave.inline(r'printf(\"%s\\n\",a);',['a'])\n    string\n    
\n\n

\nAs in this case, C/C++ code fragments often have to change to accept different \ntypes. For the given printing task, however, C++ streams provide a way of a \nsingle statement that works for integers and strings. By default, the stream \nobjects live in the std (standard) namespace and thus require the use of \nstd::.\n\n

    \n    >>> weave.inline('std::cout << a << std::endl;',['a'])\n    1    \n    >>> a = 'string'\n    >>> weave.inline('std::cout << a << std::endl;',['a'])\n    string\n    
\n \n

\nExamples using printf and cout are included in \nexamples/print_example.py.\n\n\n

More examples

\n\nThis section shows several more advanced uses of inline. It \nincludes a few algorithms from the Python Cookbook \nthat have been re-written in inline C to improve speed as well as a couple \nexamples using Numeric and wxPython.\n\n\n

Binary search

\nLets look at the example of searching a sorted list of integers for a value. \nFor inspiration, we'll use Kalle Svensson's \nbinary_search() algorithm from the Python Cookbook. His recipe follows:\n\n
\n    def binary_search(seq, t):\n        min = 0; max = len(seq) - 1\n        while 1:\n            if max < min:\n                return -1\n            m = (min  + max)  / 2\n            if seq[m] < t: \n                min = m  + 1 \n            elif seq[m] > t: \n                max = m  - 1 \n            else:\n                return m    \n    
\n\nThis Python version works for arbitrary Python data types. The C version below is \nspecialized to handle integer values. There is a little type checking done in \nPython to assure that we're working with the correct data types before heading \ninto C. The variables seq and t don't need to be \ndeclared beacuse weave handles converting and declaring them in \nthe C code. All other temporary variables such as min, max, etc. \nmust be declared -- it is C after all. Here's the new mixed Python/C function:\n\n
    \n    def c_int_binary_search(seq,t):\n        # do a little type checking in Python\n        assert(type(t) == type(1))\n        assert(type(seq) == type([]))\n        \n        # now the C code\n        code = \"\"\"\n               #line 29 \"binary_search.py\"\n               int val, m, min = 0;  \n               int max = seq.length() - 1;\n               PyObject *py_val; \n               for(;;)\n               {\n                   if (max < min  ) \n                   { \n                       return_val =  Py::new_reference_to(Py::Int(-1)); \n                       break;\n                   } \n                   m =  (min + max) /2;\n                   val =    py_to_int(PyList_GetItem(seq.ptr(),m),\"val\"); \n                   if (val  < t) \n                       min = m  + 1;\n                   else if (val >  t)\n                       max = m - 1;\n                   else\n                   {\n                       return_val = Py::new_reference_to(Py::Int(m));\n                       break;\n                   }\n               }\n               \"\"\"\n        return inline(code,['seq','t'])\n    
\n

\nWe have two variables seq and t passed in. \nt is guaranteed (by the assert) to be an integer. \nPython integers are converted to C int types in the transition from Python to \nC. seq is a Python list. By default, it is translated to a CXX \nlist object. Full documentation for the CXX library can be found at its website. The basics are that the CXX \nprovides C++ class equivalents for Python objects that simplify, or at \nleast object orientify, working with Python objects in C/C++. For example, \nseq.length() returns the length of the list. A little more about\nCXX and its class methods, etc. is in the ** type conversions ** section.\n

\n\nNote: CXX uses templates and therefore may be a little less portable than \nanother alternative by Gordan McMillan called SCXX which was inspired by\nCXX. It doesn't use templates so it should compile faster and be more portable.\nSCXX has a few less features, but it appears to me that it would mesh with\nthe needs of weave quite well. Hopefully xxx_spec files will be written\nfor SCXX in the future, and we'll be able to compare on a more empirical\nbasis. Both sets of spec files will probably stick around, it just a question\nof which becomes the default.\n\n

\nMost of the algorithm above looks similar in C to the original Python code. \nThere are two main differences. The first is the setting of \nreturn_val instead of directly returning from the C code with a \nreturn statement. return_val is an automatically \ndefined variable of type PyObject* that is returned from the C \ncode back to Python. You'll have to handle reference counting issues when \nsetting this variable. In this example, CXX classes and functions handle the \ndirty work. All CXX functions and classes live in the namespace \nPy::. The following code converts the integer m to a \nCXX Int() object and then to a PyObject* with an \nincremented reference count using Py::new_reference_to().\n\n

   \n    return_val = Py::new_reference_to(Py::Int(m));\n    
\n

\nThe second big differences shows up in the retrieval of integer values from the \nPython list. The simple Python seq[i] call balloons into a C \nPython API call to grab the value out of the list and then a separate call to \npy_to_int() that converts the PyObject* to an integer. \npy_to_int() includes both a NULL cheack and a \nPyInt_Check() call as well as the conversion call. If either of \nthe checks fail, an exception is raised. The entire C++ code block is executed \nwith in a try/catch block that handles exceptions much like Python \ndoes. This removes the need for most error checking code.\n

\nIt is worth note that CXX lists do have indexing operators that result \nin code that looks much like Python. However, the overhead in using them \nappears to be relatively high, so the standard Python API was used on the \nseq.ptr() which is the underlying PyObject* of the \nList object.\n

\nThe #line directive that is the first line of the C code \nblock isn't necessary, but it's nice for debugging. If the compilation fails \nbecause of the syntax error in the code, the error will be reported as an error \nin the Python file \"binary_search.py\" with an offset from the given line number \n(29 here).\n

\nSo what was all our effort worth in terms of efficiency? Well not a lot in \nthis case. The examples/binary_search.py file runs both Python and C versions \nof the functions As well as using the standard bisect module. If \nwe run it on a 1 million element list and run the search 3000 times (for 0-\n2999), here are the results we get:\n\n

   \n    C:\\home\\ej\\wrk\\scipy\\weave\\examples> python binary_search.py\n    Binary search for 3000 items in 1000000 length list of integers:\n     speed in python: 0.159999966621\n     speed of bisect: 0.121000051498\n     speed up: 1.32\n     speed in c: 0.110000014305\n     speed up: 1.45\n     speed in c(no asserts): 0.0900000333786\n     speed up: 1.78\n    
\n

\nSo, we get roughly a 50-75% improvement depending on whether we use the Python \nasserts in our C version. If we move down to searching a 10000 element list, \nthe advantage evaporates. Even smaller lists might result in the Python \nversion being faster. I'd like to say that moving to Numeric lists (and \ngetting rid of the GetItem() call) offers a substantial speed up, but my \npreliminary efforts didn't produce one. I think the log(N) algorithm is to \nblame. Because the algorithm is nice, there just isn't much time spent \ncomputing things, so moving to C isn't that big of a win. If there are ways to \nreduce conversion overhead of values, this may improve the C/Python speed \nup. Anyone have other explanations or faster code, please let me know.\n\n\n

Dictionary Sort

\n

\nThe demo in examples/dict_sort.py is another example from the Python CookBook. \nThis \nsubmission, by Alex Martelli, demonstrates how to return the values from a \ndictionary sorted by their keys:\n\n

       \n    def sortedDictValues3(adict):\n        keys = adict.keys()\n        keys.sort()\n        return map(adict.get, keys)\n    
\n

\nAlex provides 3 algorithms and this is the 3rd and fastest of the set. The C \nversion of this same algorithm follows:\n\n

       \n    def c_sort(adict):\n        assert(type(adict) == type({}))\n        code = \"\"\"     \n        #line 21 \"dict_sort.py\"  \n        Py::List keys = adict.keys();\n        Py::List items(keys.length()); keys.sort();     \n        PyObject* item = NULL; \n        for(int i = 0;  i < keys.length();i++)\n        {\n            item = PyList_GET_ITEM(keys.ptr(),i);\n            item = PyDict_GetItem(adict.ptr(),item);\n            Py_XINCREF(item);\n            PyList_SetItem(items.ptr(),i,item);              \n        }           \n        return_val = Py::new_reference_to(items);\n        \"\"\"   \n        return inline_tools.inline(code,['adict'],verbose=1)\n    
\n

\nLike the original Python function, the C++ version can handle any Python \ndictionary regardless of the key/value pair types. It uses CXX objects for the \nmost part to declare python types in C++, but uses Python API calls to manipulate \ntheir contents. Again, this choice is made for speed. The C++ version, while\nmore complicated, is about a factor of 2 faster than Python.\n\n

       \n    C:\\home\\ej\\wrk\\scipy\\weave\\examples> python dict_sort.py\n    Dict sort of 1000 items for 300 iterations:\n     speed in python: 0.319999933243\n    [0, 1, 2, 3, 4]\n     speed in c: 0.151000022888\n     speed up: 2.12\n    [0, 1, 2, 3, 4]\n    
\n

\n\n

Numeric -- cast/copy/transpose

\n\nCastCopyTranspose is a function called quite heavily by Linear Algebra routines\nin the Numeric library. Its needed in part because of the row-major memory layout\nof multi-demensional Python (and C) arrays vs. the col-major order of the underlying\nFortran algorithms. For small matrices (say 100x100 or less), a significant\nportion of the common routines such as LU decompisition or singular value decompostion\nare spent in this setup routine. This shouldn't happen. Here is the Python\nversion of the function using standard Numeric operations.\n\n
       \n    def _castCopyAndTranspose(type, array):\n        if a.typecode() == type:\n            cast_array = copy.copy(Numeric.transpose(a))\n        else:\n            cast_array = copy.copy(Numeric.transpose(a).astype(type))\n        return cast_array\n    
\n\nAnd the following is a inline C version of the same function:\n\n
\n    from weave.blitz_tools import blitz_type_factories\n    from weave import scalar_spec\n    from weave import inline\n    def _cast_copy_transpose(type,a_2d):\n        assert(len(shape(a_2d)) == 2)\n        new_array = zeros(shape(a_2d),type)\n        numeric_type = scalar_spec.numeric_to_blitz_type_mapping[type]\n        code = \\\n        \"\"\"  \n        for(int i = 0;i < _Na_2d[0]; i++)  \n            for(int j = 0;  j < _Na_2d[1]; j++)\n                new_array(i,j) = (%s) a_2d(j,i);\n        \"\"\" % numeric_type\n        inline(code,['new_array','a_2d'],\n               type_factories = blitz_type_factories,compiler='gcc')\n        return new_array\n    
\n\nThis example uses blitz++ arrays instead of the standard representation of \nNumeric arrays so that indexing is simplier to write. This is accomplished by \npassing in the blitz++ \"type factories\" to override the standard Python to C++ \ntype conversions. Blitz++ arrays allow you to write clean, fast code, but they \nalso are sloooow to compile (20 seconds or more for this snippet). This is why \nthey aren't the default type used for Numeric arrays (and also because most \ncompilers can't compile blitz arrays...). inline() is also forced \nto use 'gcc' as the compiler because the default compiler on Windows (MSVC) \nwill not compile blitz code. 'gcc' I think will use the standard compiler \non Unix machine instead of explicitly forcing gcc (check this) \n\nComparisons of the Python vs inline C++ code show a factor of 3 speed up. Also \nshown are the results of an \"inplace\" transpose routine that can be used if the \noutput of the linear algebra routine can overwrite the original matrix (this is \noften appropriate). This provides another factor of 2 improvement.\n\n
\n     #C:\\home\\ej\\wrk\\scipy\\weave\\examples> python cast_copy_transpose.py\n    # Cast/Copy/Transposing (150,150)array 1 times\n    #  speed in python: 0.870999932289\n    #  speed in c: 0.25\n    #  speed up: 3.48\n    #  inplace transpose c: 0.129999995232\n    #  speed up: 6.70\n    
\n\n\n

wxPython

\n\ninline knows how to handle wxPython objects. Thats nice in and of\nitself, but it also demonstrates that the type conversion mechanism is reasonably \nflexible. Chances are, it won't take a ton of effort to support special types\nyou might have. The examples/wx_example.py borrows the scrolled window\nexample from the wxPython demo, accept that it mixes inline C code in the middle\nof the drawing function.\n\n
\n    def DoDrawing(self, dc):\n        \n        red = wxNamedColour(\"RED\");\n        blue = wxNamedColour(\"BLUE\");\n        grey_brush = wxLIGHT_GREY_BRUSH;\n        code = \\\n        \"\"\"\n        #line 108 \"wx_example.py\" \n        dc->BeginDrawing();\n        dc->SetPen(wxPen(*red,4,wxSOLID));\n        dc->DrawRectangle(5,5,50,50);\n        dc->SetBrush(*grey_brush);\n        dc->SetPen(wxPen(*blue,4,wxSOLID));\n        dc->DrawRectangle(15, 15, 50, 50);\n        \"\"\"\n        inline(code,['dc','red','blue','grey_brush'])\n        \n        dc.SetFont(wxFont(14, wxSWISS, wxNORMAL, wxNORMAL))\n        dc.SetTextForeground(wxColour(0xFF, 0x20, 0xFF))\n        te = dc.GetTextExtent(\"Hello World\")\n        dc.DrawText(\"Hello World\", 60, 65)\n\n        dc.SetPen(wxPen(wxNamedColour('VIOLET'), 4))\n        dc.DrawLine(5, 65+te[1], 60+te[0], 65+te[1])\n        ...\n    
\n\nHere, some of the Python calls to wx objects were just converted to C++ calls. There\nisn't any benefit, it just demonstrates the capabilities. You might want to use this\nif you have a computationally intensive loop in your drawing code that you want to \nspeed up.\n\nOn windows, you'll have to use the MSVC compiler if you use the standard wxPython\nDLLs distributed by Robin Dunn. Thats because MSVC and gcc, while binary\ncompatible in C, are not binary compatible for C++. In fact, its probably best, no \nmatter what platform you're on, to specify that inline use the same\ncompiler that was used to build wxPython to be on the safe side. There isn't currently\na way to learn this info from the library -- you just have to know. Also, at least\non the windows platform, you'll need to install the wxWindows libraries and link to \nthem. I think there is a way around this, but I haven't found it yet -- I get some\nlinking errors dealing with wxString. One final note. You'll probably have to\ntweak weave/wx_spec.py or weave/wx_info.py for your machine's configuration to\npoint at the correct directories etc. There. That should sufficiently scare people\ninto not even looking at this... :)\n\n
\n

Keyword Options

\n

\nThe basic definition of the inline() function has a slew of \noptional variables. It also takes keyword arguments that are passed to \ndistutils as compiler options. The following is a formatted \ncut/paste of the argument section of inline's doc-string. It \nexplains all of the variables. Some examples using various options will \nfollow.\n\n

       \n    def inline(code,arg_names,local_dict = None, global_dict = None, \n               force = 0, \n               compiler='',\n               verbose = 0, \n               support_code = None,\n               customize=None, \n               type_factories = None, \n               auto_downcast=1,\n               **kw):\n    
\n\n \ninline has quite \na few options as listed below. Also, the keyword arguments for distutils \nextension modules are accepted to specify extra information needed for \ncompiling. \n
\n

inline Arguments:

\n
\n
\n
code
\n \n
\nstring. A string of valid C++ code. It should not \n specify a return statement. Instead it should assign results that need to be \n returned to Python in the return_val. \n
\n\n
arg_names
\n \n
\nlist of strings. A list of Python variable names \n that should be transferred from Python into the C/C++ code. \n
\n\n
local_dict
\n \n
\noptional. dictionary. If specified, it is a \n dictionary of values that should be used as the local scope for the C/C++ \n code. If local_dict is not specified the local dictionary of the calling \n function is used. \n
\n\n
global_dict
\n \n
\noptional. dictionary. If specified, it is a \n dictionary of values that should be used as the global scope for the C/C++ \n code. If global_dict is not specified the global dictionary of the calling \n function is used. \n
\n\n
force
\n \n
\noptional. 0 or 1. default 0. If 1, the C++ code is \n compiled every time inline is called. This is really only useful for \n debugging, and probably only useful if you're editing support_code a lot. \n
\n\n
compiler
\n \n
\noptional. string. The name of compiler to use when compiling. On windows, it \nunderstands 'msvc' and 'gcc' as well as all the compiler names understood by \ndistutils. On Unix, it'll only understand the values understoof by distutils. \n(I should add 'gcc' though to this).\n

\nOn windows, the compiler defaults to the Microsoft C++ compiler. If this isn't \navailable, it looks for mingw32 (the gcc compiler).\n

\nOn Unix, it'll probably use the same compiler that was used when compiling \nPython. Cygwin's behavior should be similar.

\n
\n\n
verbose
\n \n
\noptional. 0,1, or 2. defualt 0. Speficies how much \n much information is printed during the compile phase of inlining code. 0 is \n silent (except on windows with msvc where it still prints some garbage). 1 \n informs you when compiling starts, finishes, and how long it took. 2 prints \n out the command lines for the compilation process and can be useful if you're \n having problems getting code to work. Its handy for finding the name of the \n .cpp file if you need to examine it. verbose has no affect if the \n compilation isn't necessary. \n
\n\n
support_code
\n \n
\noptional. string. A string of valid C++ code \n declaring extra code that might be needed by your compiled function. This \n could be declarations of functions, classes, or structures. \n
\n\n
customize
\n \n
\noptional. base_info.custom_info object. An \n alternative way to specifiy support_code, headers, etc. needed by the \n function see the weave.base_info module for more details. (not sure \n this'll be used much). \n \n
\n
type_factories
\n \n
\noptional. list of type specification factories. These guys are what convert \nPython data types to C/C++ data types. If you'd like to use a different set of \ntype conversions than the default, specify them here. Look in the type \nconversions section of the main documentation for examples.\n
\n
auto_downcast
\n \n
\noptional. 0 or 1. default 1. This only affects functions that have Numeric \narrays as input variables. Setting this to 1 will cause all floating point \nvalues to be cast as float instead of double if all the Numeric arrays are of \ntype float. If even one of the arrays has type double or double complex, all \nvariables maintain there standard types.\n
\n
\n
\n\n

Distutils keywords:

\n
\ninline() also accepts a number of distutils keywords \nfor controlling how the code is compiled. The following descriptions have been \ncopied from Greg Ward's distutils.extension.Extension class doc-\nstrings for convenience:\n\n
\n
sources
\n \n
\n[string] list of source filenames, relative to the \n distribution root (where the setup script lives), in Unix form \n (slash-separated) for portability. Source files may be C, C++, SWIG (.i), \n platform-specific resource files, or whatever else is recognized by the \n \"build_ext\" command as source for a Python extension. Note: The module_path \n file is always appended to the front of this list \n
\n\n
include_dirs
\n \n
\n[string] list of directories to search for C/C++ \n header files (in Unix form for portability) \n
\n\n
define_macros
\n \n
\n[(name : string, value : string|None)] list of \n macros to define; each macro is defined using a 2-tuple, where 'value' is \n either the string to define it to or None to define it without a particular \n value (equivalent of \"#define FOO\" in source or -DFOO on Unix C compiler \n command line) \n
\n
undef_macros
\n \n
\n[string] list of macros to undefine explicitly \n
\n
library_dirs
\n
\n[string] list of directories to search for C/C++ libraries at link time \n
\n
libraries
\n
\n[string] list of library names (not filenames or paths) to link against \n
\n
runtime_library_dirs
\n
\n[string] list of directories to search for C/C++ libraries at run time (for \nshared extensions, this is when the extension is loaded) \n
\n\n
extra_objects
\n \n
\n[string] list of extra files to link with (eg. \n object files not implied by 'sources', static library that must be \n explicitly specified, binary resource files, etc.) \n
\n\n
extra_compile_args
\n \n
\n[string] any extra platform- and compiler-specific \n information to use when compiling the source files in 'sources'. For \n platforms and compilers where \"command line\" makes sense, this is typically \n a list of command-line arguments, but for other platforms it could be \n anything. \n
\n
extra_link_args
\n \n
\n[string] any extra platform- and compiler-specific \n information to use when linking object files together to create the \n extension (or to create a new static Python interpreter). Similar \n interpretation as for 'extra_compile_args'. \n
\n
export_symbols
\n \n
\n[string] list of symbols to be exported from a shared extension. Not used on \nall platforms, and not generally necessary for Python extensions, which \ntypically export exactly one symbol: \"init\" + extension_name. \n
\n
\n
\n\n\n

Keyword Option Examples

\nWe'll walk through several examples here to demonstrate the behavior of \ninline and also how the various arguments are used.\n\nIn the simplest (most) cases, code and arg_names\nare the only arguments that need to be specified. Here's a simple example\nrun on Windows machine that has Microsoft VC++ installed.\n\n
\n    >>> from weave import inline\n    >>> a = 'string'\n    >>> code = \"\"\"\n    ...        int l = a.length();\n    ...        return_val = Py::new_reference_to(Py::Int(l));\n    ...        \"\"\"\n    >>> inline(code,['a'])\n     sc_86e98826b65b047ffd2cd5f479c627f12.cpp\n    Creating\n       library C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e98826b65b047ffd2cd5f479c627f12.lib\n    and object C:\\DOCUME~ 1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e98826b65b047ff\n    d2cd5f479c627f12.exp\n    6\n    >>> inline(code,['a'])\n    6\n    
\n \nWhen inline is first run, you'll notice that pause and some \ntrash printed to the screen. The \"trash\" is acutually part of the compilers\noutput that distutils does not supress. The name of the extension file, \nsc_bighonkingnumber.cpp, is generated from the md5 check sum\nof the C/C++ code fragment. On Unix or windows machines with only\ngcc installed, the trash will not appear. On the second call, the code \nfragment is not compiled since it already exists, and only the answer is \nreturned. Now kill the interpreter and restart, and run the same code with\na different string.\n\n
\n    >>> from weave import inline\n    >>> a = 'a longer string' \n    >>> code = \"\"\" \n    ...        int l = a.length();\n    ...        return_val = Py::new_reference_to(Py::Int(l));  \n    ...        \"\"\"\n    >>> inline(code,['a'])\n    15\n    
\n

\nNotice this time, inline() did not recompile the code because it\nfound the compiled function in the persistent catalog of functions. There is\na short pause as it looks up and loads the function, but it is much shorter \nthan compiling would require.\n

\nYou can specify the local and global dictionaries if you'd like (much like \nexec or eval() in Python), but if they aren't \nspecified, the \"expected\" ones are used -- i.e. the ones from the function that \ncalled inline() . This is accomplished through a little call \nframe trickery. Here is an example where the local_dict is specified using\nthe same code example from above:\n\n

\n    >>> a = 'a longer string'\n    >>> b = 'an even  longer string' \n    >>> my_dict = {'a':b}\n    >>> inline(code,['a'])\n    15\n    >>> inline(code,['a'],my_dict)\n    21\n    
\n \n

\nEverytime, the code is changed, inline does a \nrecompile. However, changing any of the other options in inline does not\nforce a recompile. The force option was added so that one\ncould force a recompile when tinkering with other variables. In practice,\nit is just as easy to change the code by a single character\n(like adding a space some place) to force the recompile. Note: It also \nmight be nice to add some methods for purging the cache and on disk \ncatalogs.\n

\nI use verbose sometimes for debugging. When set to 2, it'll \noutput all the information (including the name of the .cpp file) that you'd\nexpect from running a make file. This is nice if you need to examine the\ngenerated code to see where things are going haywire. Note that error\nmessages from failed compiles are printed to the screen even if verbose\n is set to 0.\n

\nThe following example demonstrates using gcc instead of the standard msvc \ncompiler on windows using same code fragment as above. Because the example has \nalready been compiled, the force=1 flag is needed to make \ninline() ignore the previously compiled version and recompile \nusing gcc. The verbose flag is added to show what is printed out:\n\n

\n    >>>inline(code,['a'],compiler='gcc',verbose=2,force=1)\n    running build_ext    \n    building 'sc_86e98826b65b047ffd2cd5f479c627f13' extension \n    c:\\gcc-2.95.2\\bin\\g++.exe -mno-cygwin -mdll -O2 -w -Wstrict-prototypes -IC:\n    \\home\\ej\\wrk\\scipy\\weave -IC:\\Python21\\Include -c C:\\DOCUME~1\\eric\\LOCAL\n    S~1\\Temp\\python21_compiled\\sc_86e98826b65b047ffd2cd5f479c627f13.cpp -o C:\\D\n    OCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e98826b65b04\n    7ffd2cd5f479c627f13.o    \n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\cxxextensions.c (C:\\DOCUME~1\\eri\n    c\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\cxxextensions.o up-to-date)\n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\cxxsupport.cxx (C:\\DOCUME~1\\eric\n    \\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\cxxsupport.o up-to-date)\n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\IndirectPythonInterface.cxx (C:\\\n    DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\indirectpythonin\n    terface.o up-to-date)\n    skipping C:\\home\\ej\\wrk\\scipy\\weave\\CXX\\cxx_extensions.cxx (C:\\DOCUME~1\\\n    eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\cxx_extensions.o up-to-da\n    te)\n    writing C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86\n    e98826b65b047ffd2cd5f479c627f13.def\n    c:\\gcc-2.95.2\\bin\\dllwrap.exe --driver-name g++ -mno-cygwin -mdll -static -\n    -output-lib C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\l\n    ibsc_86e98826b65b047ffd2cd5f479c627f13.a --def C:\\DOCUME~1\\eric\\LOCALS~1\\Te\n    mp\\python21_compiled\\temp\\Release\\sc_86e98826b65b047ffd2cd5f479c627f13.def \n    -s C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\temp\\Release\\sc_86e9882\n    6b65b047ffd2cd5f479c627f13.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compil\n    ed\\temp\\Release\\cxxextensions.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_com\n    piled\\temp\\Release\\cxxsupport.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_com\n    piled\\temp\\Release\\indirectpythoninterface.o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\n    \\python21_compiled\\temp\\Release\\cxx_extensions.o -LC:\\Python21\\libs -lpytho\n    n21 -o C:\\DOCUME~1\\eric\\LOCALS~1\\Temp\\python21_compiled\\sc_86e98826b65b047f\n    fd2cd5f479c627f13.pyd\n    15\n    
\n\nThat's quite a bit of output. verbose=1 just prints the compile\ntime.\n\n
\n    >>>inline(code,['a'],compiler='gcc',verbose=1,force=1)\n    Compiling code...\n    finished compiling (sec):  6.00800001621\n    15\n    
\n\n

\n Note: I've only used the compiler option for switching between 'msvc'\nand 'gcc' on windows. It may have use on Unix also, but I don't know yet.\n\n\n

\nThe support_code argument is likely to be used a lot. It allows \nyou to specify extra code fragments such as function, structure or class \ndefinitions that you want to use in the code string. Note that \nchanges to support_code do not force a recompile. The \ncatalog only relies on code (for performance reasons) to determine \nwhether recompiling is necessary. So, if you make a change to support_code, \nyou'll need to alter code in some way or use the \nforce argument to get the code to recompile. I usually just add \nsome inocuous whitespace to the end of one of the lines in code \nsomewhere. Here's an example of defining a separate method for calculating\nthe string length:\n\n

\n    >>> from weave import inline\n    >>> a = 'a longer string'\n    >>> support_code = \"\"\"\n    ...                PyObject* length(Py::String a)\n    ...                {\n    ...                    int l = a.length();  \n    ...                    return Py::new_reference_to(Py::Int(l)); \n    ...                }\n    ...                \"\"\"        \n    >>> inline(\"return_val = length(a);\",['a'],\n    ...        support_code = support_code)\n    15\n    
\n

\ncustomize is a left over from a previous way of specifying \ncompiler options. It is a custom_info object that can specify \nquite a bit of information about how a file is compiled. These \ninfo objects are the standard way of defining compile information \nfor type conversion classes. However, I don't think they are as handy here, \nespecially since we've exposed all the keyword arguments that distutils can \nhandle. Between these keywords, and the support_code option, I \nthink customize may be obsolete. We'll see if anyone cares to use \nit. If not, it'll get axed in the next version.\n

\nThe type_factories variable is important to people who want to\ncustomize the way arguments are converted from Python to C. We'll talk about\nthis in the next chapter **xx** of this document when we discuss type\nconversions.\n

\nauto_downcast handles one of the big type conversion issues that\nis common when using Numeric arrays in conjunction with Python scalar values.\nIf you have an array of single precision values and multiply that array by a \nPython scalar, the result is upcast to a double precision array because the\nscalar value is double precision. This is not usually the desired behavior\nbecause it can double your memory usage. auto_downcast goes\nsome distance towards changing the casting precedence of arrays and scalars.\nIf your only using single precision arrays, it will automatically downcast all\nscalar values from double to single precision when they are passed into the\nC++ code. This is the default behavior. If you want all values to keep there\ndefault type, set auto_downcast to 0.\n

\n\n\n\n

Returning Values

\n\nPython variables in the local and global scope transfer seemlessly from Python \ninto the C++ snippets. And, if inline were to completely live up\nto its name, any modifications to variables in the C++ code would be reflected\nin the Python variables when control was passed back to Python. For example,\nthe desired behavior would be something like:\n\n
\n    # THIS DOES NOT WORK\n    >>> a = 1\n    >>> weave.inline(\"a++;\",['a'])\n    >>> a\n    2\n    
\n\nInstead you get:\n\n
\n    >>> a = 1\n    >>> weave.inline(\"a++;\",['a'])\n    >>> a\n    1\n    
\n \nVariables are passed into C++ as if you are calling a Python function. Python's \ncalling convention is sometimes called \"pass by assignment\". This means its as \nif a c_a = a assignment is made right before inline \ncall is made and the c_a variable is used within the C++ code. \nThus, any changes made to c_a are not reflected in Python's \na variable. Things do get a little more confusing, however, when \nlooking at variables with mutable types. Changes made in C++ to the contents \nof mutable types are reflected in the Python variables.\n\n
\n    >>> a= [1,2]\n    >>> weave.inline(\"PyList_SetItem(a.ptr(),0,PyInt_FromLong(3));\",['a'])\n    >>> print a\n    [3, 2]\n    
\n\nSo modifications to the contents of mutable types in C++ are seen when control\nis returned to Python. Modifications to immutable types such as tuples,\nstrings, and numbers do not alter the Python variables.\n\nIf you need to make changes to an immutable variable, you'll need to assign\nthe new value to the \"magic\" variable return_val in C++. This\nvalue is returned by the inline() function:\n\n
\n    >>> a = 1\n    >>> a = weave.inline(\"return_val = Py::new_reference_to(Py::Int(a+1));\",['a'])  \n    >>> a\n    2\n    
\n\nThe return_val variable can also be used to return newly created \nvalues. This is possible by returning a tuple. The following trivial example \nillustrates how this can be done:\n\n
       \n    # python version\n    def multi_return():\n        return 1, '2nd'\n    \n    # C version.\n    def c_multi_return():    \n        code =  \"\"\"\n     \t        Py::Tuple results(2);\n     \t        results[0] = Py::Int(1);\n     \t        results[1] = Py::String(\"2nd\");\n     \t        return_val = Py::new_reference_to(results); \t        \n                \"\"\"\n        return inline_tools.inline(code)\n    
\n

\nThe example is available in examples/tuple_return.py. It also\nhas the dubious honor of demonstrating how much inline() can \nslow things down. The C version here is about 10 times slower than the Python\nversion. Of course, something so trivial has no reason to be written in\nC anyway.\n\n\n

The issue with locals()

\n

\ninline passes the locals() and globals() \ndictionaries from Python into the C++ function from the calling function. It \nextracts the variables that are used in the C++ code from these dictionaries, \nconverts then to C++ variables, and then calculates using them. It seems like \nit would be trivial, then, after the calculations were finished to then insert \nthe new values back into the locals() and globals() \ndictionaries so that the modified values were reflected in Python. \nUnfortunately, as pointed out by the Python manual, the locals() dictionary is \nnot writable. \n

\n\nI suspect locals() is not writable because there are some \noptimizations done to speed lookups of the local namespace. I'm guessing local \nlookups don't always look at a dictionary to find values. Can someone \"in the \nknow\" confirm or correct this? Another thing I'd like to know is whether there \nis a way to write to the local namespace of another stack frame from C/C++. If \nso, it would be possible to have some clean up code in compiled functions that \nwrote final values of variables in C++ back to the correct Python stack frame. \nI think this goes a long way toward making inline truely live up \nto its name. I don't think we'll get to the point of creating variables in \nPython for variables created in C -- although I suppose with a C/C++ parser you \ncould do that also.\n\n

\n\n\n

A quick look at the code

\n\nweave generates a C++ file holding an extension function for \neach inline code snippet. These file names are generated using \nfrom the md5 signature of the code snippet and saved to a location specified by \nthe PYTHONCOMPILED environment variable (discussed later). The cpp files are \ngenerally about 200-400 lines long and include quite a few functions to support \ntype conversions, etc. However, the actual compiled function is pretty simple. \nBelow is the familiar printf example:\n\n
\n    >>> import weave    \n    >>> a = 1\n    >>> weave.inline('printf(\"%d\\\\n\",a);',['a'])\n    1\n    
\n\nAnd here is the extension function generated by inline:\n\n
\n    static PyObject* compiled_func(PyObject*self, PyObject* args)\n    {\n        // The Py_None needs an incref before returning\n        PyObject *return_val = NULL;\n        int exception_occured = 0;\n        PyObject *py__locals = NULL;\n        PyObject *py__globals = NULL;\n        PyObject *py_a;\n        py_a = NULL;\n        \n        if(!PyArg_ParseTuple(args,\"OO:compiled_func\",&py__locals,&py__globals))\n            return NULL;\n        try                              \n        {                                \n            PyObject* raw_locals = py_to_raw_dict(py__locals,\"_locals\");\n            PyObject* raw_globals = py_to_raw_dict(py__globals,\"_globals\");\n            int a = py_to_int (get_variable(\"a\",raw_locals,raw_globals),\"a\");\n            /* Here is the inline code */            \n            printf(\"%d\\n\",a);\n            /* I would like to fill in changed locals and globals here... */\n        }                                       \n        catch( Py::Exception& e)           \n        {                                \n            return_val =  Py::Null();    \n            exception_occured = 1;       \n        }                                 \n        if(!return_val && !exception_occured)\n        {\n                                      \n            Py_INCREF(Py_None);              \n            return_val = Py_None;            \n        }\n        /* clean up code */\n        \n        /* return */                              \n        return return_val;           \n    }                                \n    
\n\nEvery inline function takes exactly two arguments -- the local and global\ndictionaries for the current scope. All variable values are looked up out\nof these dictionaries. The lookups, along with all inline code \nexecution, are done within a C++ try block. If the variables\naren't found, or there is an error converting a Python variable to the \nappropriate type in C++, an exception is raised. The C++ exception\nis automatically converted to a Python exception by CXX and returned to Python.\n\nThe py_to_int() function illustrates how the conversions and\nexception handling works. py_to_int first checks that the given PyObject*\npointer is not NULL and is a Python integer. If all is well, it calls the\nPython API to convert the value to an int. Otherwise, it calls\nhandle_bad_type() which gathers information about what went wrong\nand then raises a CXX TypeError which returns to Python as a TypeError.\n\n
\n    int py_to_int(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyInt_Check(py_obj))\n            handle_bad_type(py_obj,\"int\", name);\n        return (int) PyInt_AsLong(py_obj);\n    }\n    
\n\n
\n    void handle_bad_type(PyObject* py_obj, char* good_type, char*  var_name)\n    {\n        char msg[500];\n        sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n                find_type(py_obj),good_type,var_name);\n        throw Py::TypeError(msg);\n    }\n    \n    char* find_type(PyObject* py_obj)\n    {\n        if(py_obj == NULL) return \"C NULL value\";\n        if(PyCallable_Check(py_obj)) return \"callable\";\n        if(PyString_Check(py_obj)) return \"string\";\n        if(PyInt_Check(py_obj)) return \"int\";\n        if(PyFloat_Check(py_obj)) return \"float\";\n        if(PyDict_Check(py_obj)) return \"dict\";\n        if(PyList_Check(py_obj)) return \"list\";\n        if(PyTuple_Check(py_obj)) return \"tuple\";\n        if(PyFile_Check(py_obj)) return \"file\";\n        if(PyModule_Check(py_obj)) return \"module\";\n        \n        //should probably do more interagation (and thinking) on these.\n        if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n        if(PyInstance_Check(py_obj)) return \"instance\"; \n        if(PyCallable_Check(py_obj)) return \"callable\";\n        return \"unkown type\";\n    }\n    
\n\nSince the inline is also executed within the try/catch\nblock, you can use CXX exceptions within your code. It is usually a bad idea\nto directly return from your code, even if an error occurs. This\nskips the clean up section of the extension function. In this simple example,\nthere isn't any clean up code, but in more complicated examples, there may\nbe some reference counting that needs to be taken care of here on converted\nvariables. To avoid this, either uses exceptions or set \nreturn_val to NULL and use if/then's to skip code\nafter errors.\n\n\n

Technical Details

\n

\nThere are several main steps to using C/C++ code withing Python:\n

    \n
  1. Type conversion \n
  2. Generating C/C++ code \n
  3. Compile the code to an extension module \n
  4. Catalog (and cache) the function for future use
  5. \n
\n

\nItems 1 and 2 above are related, but most easily discussed separately. Type \nconversions are customizable by the user if needed. Understanding them is \npretty important for anything beyond trivial uses of inline. \nGenerating the C/C++ code is handled by ext_function and \next_module classes and . For the most part, compiling the code is \nhandled by distutils. Some customizations were needed, but they were \nrelatively minor and do not require changes to distutils itself. Cataloging is \npretty simple in concept, but surprisingly required the most code to implement \n(and still likely needs some work). So, this section covers items 1 and 4 from \nthe list. Item 2 is covered later in the chapter covering the \next_tools module, and distutils is covered by a completely \nseparate document xxx.\n\n

Passing Variables in/out of the C/C++ code

\n\nNote: Passing variables into the C code is pretty straight forward, but there \nare subtlties to how variable modifications in C are returned to Python. see Returning Values for a more thorough discussion of \nthis issue.\n \n \n\n

Type Conversions

\n\n\nNote: Maybe xxx_converter instead of \nxxx_specification is a more descriptive name. Might change in \nfuture version?\n\n\n

\nBy default, inline() makes the following type conversions between\nPython and C++ types.\n

\n\n

\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
\n

Default Data Type Conversions

\n

Python

\n

C++

   int   int
   float   double
   complex   std::complex
   string   Py::String
   list   Py::List
   dict   Py::Dict
   tuple   Py::Tuple
   file   FILE*
   callable   PyObject*
   instance   PyObject*
   Numeric.array   PyArrayObject*
   wxXXX   wxXXX*
\n
\n

\nThe Py:: namespace is defined by the \nCXX library which has C++ class\nequivalents for many Python types. std:: is the namespace of the\nstandard library in C++.\n

\n\nNote: \n

    \n
  • I haven't figured out how to handle long int yet (I think they are currenlty converted \n to int - - check this). \n \n
  • \nHopefully VTK will be added to the list soon
  • \n
\n\n

\n\nPython to C++ conversions fill in code in several locations in the generated\ninline extension function. Below is the basic template for the\nfunction. This is actually the exact code that is generated by calling\nweave.inline(\"\").\n\n

\n    static PyObject* compiled_func(PyObject*self, PyObject* args)\n    {\n        PyObject *return_val = NULL;\n        int exception_occured = 0;\n        PyObject *py__locals = NULL;\n        PyObject *py__globals = NULL;\n        PyObject *py_a;\n        py_a = NULL;\n    \n        if(!PyArg_ParseTuple(args,\"OO:compiled_func\",&py__locals,&py__globals))\n            return NULL;\n        try\n        {\n            PyObject* raw_locals = py_to_raw_dict(py__locals,\"_locals\");\n            PyObject* raw_globals = py_to_raw_dict(py__globals,\"_globals\");\n            /* argument conversion code */\n            /* inline code */\n            /*I would like to fill in changed locals and globals here...*/\n    \n        }\n        catch( Py::Exception& e)\n        {\n            return_val =  Py::Null();\n            exception_occured = 1;\n        }\n        /* cleanup code */\n        if(!return_val && !exception_occured)\n        {\n    \n            Py_INCREF(Py_None);\n            return_val = Py_None;\n        }\n    \n        return return_val;\n    }\n    
\n\nThe /* inline code */ section is filled with the code passed to\nthe inline() function call. The \n/*argument convserion code*/ and /* cleanup code */\nsections are filled with code that handles conversion from Python to C++\ntypes and code that deallocates memory or manipulates reference counts before\nthe function returns. The following sections demostrate how these two areas\nare filled in by the default conversion methods.\n\n \nNote: I'm not sure I have reference counting correct on a few of these. The \nonly thing I increase/decrease the ref count on is Numeric arrays. If you\nsee an issue, please let me know.\n\n\n\n

Numeric Argument Conversion

\n\nInteger, floating point, and complex arguments are handled in a very similar\nfashion. Consider the following inline function that has a single integer \nvariable passed in:\n\n
\n    >>> a = 1\n    >>> inline(\"\",['a'])\n    
\n\nThe argument conversion code inserted for a is:\n\n
\n    /* argument conversion code */\n    int a = py_to_int (get_variable(\"a\",raw_locals,raw_globals),\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. py_to_int() has the following\nform:\n\n
\n    static int py_to_int(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyInt_Check(py_obj))\n            handle_bad_type(py_obj,\"int\", name);\n        return (int) PyInt_AsLong(py_obj);\n    }\n    
\n\nSimilarly, the float and complex conversion routines look like:\n\n
    \n    static double py_to_float(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyFloat_Check(py_obj))\n            handle_bad_type(py_obj,\"float\", name);\n        return PyFloat_AsDouble(py_obj);\n    }\n    \n    static std::complex py_to_complex(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyComplex_Check(py_obj))\n            handle_bad_type(py_obj,\"complex\", name);\n        return std::complex(PyComplex_RealAsDouble(py_obj),\n                                    PyComplex_ImagAsDouble(py_obj));    \n    }\n    
\n\nNumeric conversions do not require any clean up code.\n\n\n

String, List, Tuple, and Dictionary Conversion

\n\nStrings, Lists, Tuples and Dictionary conversions are all converted to \nCXX types by default.\n\nFor the following code, \n\n
\n    >>> a = [1]\n    >>> inline(\"\",['a'])\n    
\n\nThe argument conversion code inserted for a is:\n\n
\n    /* argument conversion code */\n    Py::List a = py_to_list (get_variable(\"a\",raw_locals,raw_globals),\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. py_to_list() and its\nfriends has the following form:\n\n
    \n    static Py::List py_to_list(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyList_Check(py_obj))\n            handle_bad_type(py_obj,\"list\", name);\n        return Py::List(py_obj);\n    }\n    \n    static Py::String py_to_string(PyObject* py_obj,char* name)\n    {\n        if (!PyString_Check(py_obj))\n            handle_bad_type(py_obj,\"string\", name);\n        return Py::String(py_obj);\n    }\n\n    static Py::Dict py_to_dict(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyDict_Check(py_obj))\n            handle_bad_type(py_obj,\"dict\", name);\n        return Py::Dict(py_obj);\n    }\n    \n    static Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n    {\n        if (!py_obj || !PyTuple_Check(py_obj))\n            handle_bad_type(py_obj,\"tuple\", name);\n        return Py::Tuple(py_obj);\n    }\n    
\n\nCXX handles reference counts on for strings, lists, tuples, and dictionaries,\nso clean up code isn't necessary.\n\n\n

File Conversion

\n\nFor the following code, \n\n
\n    >>> a = open(\"bob\",'w')  \n    >>> inline(\"\",['a'])\n    
\n\nThe argument conversion code is:\n\n
\n    /* argument conversion code */\n    PyObject* py_a = get_variable(\"a\",raw_locals,raw_globals);\n    FILE* a = py_to_file(py_a,\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. py_to_file() converts\nPyObject* to a FILE* and increments the reference count of the PyObject*:\n\n
\n    FILE* py_to_file(PyObject* py_obj, char* name)\n    {\n        if (!py_obj || !PyFile_Check(py_obj))\n            handle_bad_type(py_obj,\"file\", name);\n    \n        Py_INCREF(py_obj);\n        return PyFile_AsFile(py_obj);\n    }\n    
\n\nBecause the PyObject* was incremented, the clean up code needs to decrement\nthe counter\n\n
\n    /* cleanup code */\n    Py_XDECREF(py_a);\n    
\n\nIts important to understand that file conversion only works on actual files --\ni.e. ones created using the open() command in Python. It does\nnot support converting arbitrary objects that support the file interface into\nC FILE* pointers. This can affect many things. For example, in\ninitial printf() examples, one might be tempted to solve the \nproblem of C and Python IDE's (PythonWin, PyCrust, etc.) writing to different\nstdout and stderr by using fprintf() and passing in \nsys.stdout and sys.stderr. For example, instead of\n\n
\n    >>> weave.inline('printf(\"hello\\\\n\");')\n    
\n \nYou might try:\n\n
\n    >>> buf = sys.stdout\n    >>> weave.inline('fprintf(buf,\"hello\\\\n\");',['buf'])\n    
\n\nThis will work as expected from a standard python interpreter, but in PythonWin,\nthe following occurs:\n\n
\n    >>> buf = sys.stdout\n    >>> weave.inline('fprintf(buf,\"hello\\\\n\");',['buf'])\n    Traceback (most recent call last):\n        File \"\", line 1, in ?\n        File \"C:\\Python21\\weave\\inline_tools.py\", line 315, in inline\n            auto_downcast = auto_downcast,\n        File \"C:\\Python21\\weave\\inline_tools.py\", line 386, in compile_function\n            type_factories = type_factories)\n        File \"C:\\Python21\\weave\\ext_tools.py\", line 197, in __init__\n            auto_downcast, type_factories)\n        File \"C:\\Python21\\weave\\ext_tools.py\", line 390, in assign_variable_types\n            raise TypeError, format_error_msg(errors)\n        TypeError: {'buf': \"Unable to convert variable 'buf' to a C++ type.\"}\n    
\n\nThe traceback tells us that inline() was unable to convert 'buf' to a\nC++ type (If instance conversion was implemented, the error would have occurred at \nruntime instead). Why is this? Let's look at what the buf object \nreally is:\n\n
\n    >>> buf\n    pywin.framework.interact.InteractiveView instance at 00EAD014\n    
\n\nPythonWin has reassigned sys.stdout to a special object that \nimplements the Python file interface. This works great in Python, but since \nthe special object doesn't have a FILE* pointer underlying it, fprintf doesn't \nknow what to do with it (well this will be the problem when instance conversion \nis implemented...).\n\n\n

Callable, Instance, and Module Conversion

\n\nNote: Need to look into how ref counts should be handled. Also,\nInstance and Module conversion are not currently implemented.\n\n\n
\n    >>> def a(): \n        pass\n    >>> inline(\"\",['a'])\n    
\n\nCallable and instance variables are converted to PyObject*. Nothing is done\nto there reference counts.\n\n
\n    /* argument conversion code */\n    PyObject* a = py_to_callable(get_variable(\"a\",raw_locals,raw_globals),\"a\");\n    
\n\nget_variable() reads the variable a\nfrom the local and global namespaces. The py_to_callable() and\npy_to_instance() don't currently increment the ref count.\n\n
    \n    PyObject* py_to_callable(PyObject* py_obj, char* name)\n    {\n        if (!py_obj || !PyCallable_Check(py_obj))\n            handle_bad_type(py_obj,\"callable\", name);    \n        return py_obj;\n    }\n\n    PyObject* py_to_instance(PyObject* py_obj, char* name)\n    {\n        if (!py_obj || !PyFile_Check(py_obj))\n            handle_bad_type(py_obj,\"instance\", name);    \n        return py_obj;\n    }\n    
\n \nThere is no cleanup code for callables, modules, or instances.\n\n\n

Customizing Conversions

\n

\nConverting from Python to C++ types is handled by xxx_specification classes. A \ntype specification class actually serve in two related but different \nroles. The first is in determining whether a Python variable that needs to be \nconverted should be represented by the given class. The second is as a code \ngenerator that generate C++ code needed to convert from Python to C++ types for \na specific variable.\n

\nWhen \n\n

\n    >>> a = 1\n    >>> weave.inline('printf(\"%d\",a);',['a'])\n    
\n \nis called for the first time, the code snippet has to be compiled. In this \nprocess, the variable 'a' is tested against a list of type specifications (the \ndefault list is stored in weave/ext_tools.py). The first \nspecification in the list is used to represent the variable. \n\n

\nExamples of xxx_specification are scattered throughout numerous \n\"xxx_spec.py\" files in the weave package. Closely related to \nthe xxx_specification classes are yyy_info classes. \nThese classes contain compiler, header, and support code information necessary \nfor including a certain set of capabilities (such as blitz++ or CXX support)\nin a compiled module. xxx_specification classes have one or more\nyyy_info classes associated with them.\n\nIf you'd like to define your own set of type specifications, the current best route\nis to examine some of the existing spec and info files. Maybe looking over\nsequence_spec.py and cxx_info.py are a good place to start. After defining \nspecification classes, you'll need to pass them into inline using the \ntype_factories argument. \n\nA lot of times you may just want to change how a specific variable type is \nrepresented. Say you'd rather have Python strings converted to \nstd::string or maybe char* instead of using the CXX \nstring object, but would like all other type conversions to have default \nbehavior. This requires that a new specification class that handles strings\nis written and then prepended to a list of the default type specifications. Since\nit is closer to the front of the list, it effectively overrides the default\nstring specification.\n\nThe following code demonstrates how this is done:\n\n...\n\n\n

The Catalog

\n

\ncatalog.py has a class called catalog that helps keep \ntrack of previously compiled functions. This prevents inline() \nand related functions from having to compile functions everytime they are \ncalled. Instead, catalog will check an in memory cache to see if the function \nhas already been loaded into python. If it hasn't, then it starts searching \nthrough persisent catalogs on disk to see if it finds an entry for the given \nfunction. By saving information about compiled functions to disk, it isn't\nnecessary to re-compile functions everytime you stop and restart the interpreter.\nFunctions are compiled once and stored for future use.\n\n

\nWhen inline(cpp_code) is called the following things happen:\n

    \n
  1. \n A fast local cache of functions is checked for the last function called for \n cpp_code. If an entry for cpp_code doesn't exist in the \n cache or the cached function call fails (perhaps because the function doesn't \n have compatible types) then the next step is to check the catalog. \n
  2. \n The catalog class also keeps an in-memory cache with a list of all the \n functions compiled for cpp_code. If cpp_code has\n ever been called, then this cache will be present (loaded from disk). If\n the cache isn't present, then it is loaded from disk.\n

    \n If the cache is present, each function in the cache is \n called until one is found that was compiled for the correct argument types. If \n none of the functions work, a new function is compiled with the given argument \n types. This function is written to the on-disk catalog as well as into the \n in-memory cache.

    \n
  3. \n When a lookup for cpp_code fails, the catalog looks through \n the on-disk function catalogs for the entries. The PYTHONCOMPILED variable \n determines where to search for these catalogs and in what order. If \n PYTHONCOMPILED is not present several platform dependent locations are \n searched. All functions found for cpp_code in the path are \n loaded into the in-memory cache with functions found earlier in the search \n path closer to the front of the call list.\n

    \n If the function isn't found in the on-disk catalog, \n then the function is compiled, written to the first writable directory in the \n PYTHONCOMPILED path, and also loaded into the in-memory cache.

    \n
  4. \n
\n\n\n

Function Storage: How functions are stored in caches and on disk

\n

\nFunction caches are stored as dictionaries where the key is the entire C++\ncode string and the value is either a single function (as in the \"level 1\"\ncache) or a list of functions (as in the main catalog cache). On disk\ncatalogs are stored in the same manor using standard Python shelves.\n

\nEarly on, there was a question as to whether md5 check sums of the C++\ncode strings should be used instead of the actual code strings. I think this\nis the route inline Perl took. Some (admittedly quick) tests of the md5 vs.\nthe entire string showed that using the entire string was at least a\nfactor of 3 or 4 faster for Python. I think this is because it is more\ntime consuming to compute the md5 value than it is to do look-ups of long\nstrings in the dictionary. Look at the examples/md5_speed.py file for the\ntest run. \n\n\n

Catalog search paths and the PYTHONCOMPILED variable

\n

\nThe default location for catalog files on Unix is is ~/.pythonXX_compiled where \nXX is version of Python being used. If this directory doesn't exist, it is \ncreated the first time a catalog is used. The directory must be writable. If, \nfor any reason it isn't, then the catalog attempts to create a directory based \non your user id in the /tmp directory. The directory permissions are set so \nthat only you have access to the directory. If this fails, I think you're out of \nluck. I don't think either of these should ever fail though. On Windows, a \ndirectory called pythonXX_compiled is created in the user's temporary \ndirectory. \n

\nThe actual catalog file that lives in this directory is a Python shelve with\na platform specific name such as \"nt21compiled_catalog\" so that multiple OSes\ncan share the same file systems without trampling on each other. Along with\nthe catalog file, the .cpp and .so or .pyd files created by inline will live\nin this directory. The catalog file simply contains keys which are the C++\ncode strings with values that are lists of functions. The function lists point\nat functions within these compiled modules. Each function in the lists \nexecutes the same C++ code string, but compiled for different input variables.\n

\nYou can use the PYTHONCOMPILED environment variable to specify alternative\nlocations for compiled functions. On Unix this is a colon (':') separated\nlist of directories. On windows, it is a (';') separated list of directories.\nThese directories will be searched prior to the default directory for a\ncompiled function catalog. Also, the first writable directory in the list\nis where all new compiled function catalogs, .cpp and .so or .pyd files are\nwritten. Relative directory paths ('.' and '..') should work fine in the\nPYTHONCOMPILED variable as should environement variables.\n

\nThere is a \"special\" path variable called MODULE that can be placed in the \nPYTHONCOMPILED variable. It specifies that the compiled catalog should\nreside in the same directory as the module that called it. This is useful\nif an admin wants to build a lot of compiled functions during the build\nof a package and then install them in site-packages along with the package.\nUser's who specify MODULE in their PYTHONCOMPILED variable will have access\nto these compiled functions. Note, however, that if they call the function\nwith a set of argument types that it hasn't previously been built for, the\nnew function will be stored in their default directory (or some other writable\ndirectory in the PYTHONCOMPILED path) because the user will not have write\naccess to the site-packages directory.\n

\nAn example of using the PYTHONCOMPILED path on bash follows:\n\n

\n    PYTHONCOMPILED=MODULE:/some/path;export PYTHONCOMPILED;\n    
\n\nIf you are using python21 on linux, and the module bob.py in site-packages\nhas a compiled function in it, then the catalog search order when calling that\nfunction for the first time in a python session would be:\n\n
\n    /usr/lib/python21/site-packages/linuxpython_compiled\n    /some/path/linuxpython_compiled\n    ~/.python21_compiled/linuxpython_compiled\n    
\n\nThe default location is always included in the search path.\n

\n \nNote: hmmm. see a possible problem here. I should probably make a sub-\ndirectory such as /usr/lib/python21/site-\npackages/python21_compiled/linuxpython_compiled so that library files compiled \nwith python21 are tried to link with python22 files in some strange scenarios. \nNeed to check this.\n\n\n

\nThe in-module cache (in weave.inline_tools reduces the overhead \nof calling inline functions by about a factor of 2. It can be reduced a little \nmore for type loop calls where the same function is called over and over again \nif the cache was a single value instead of a dictionary, but the benefit is \nvery small (less than 5%) and the utility is quite a bit less. So, we'll stick \nwith a dictionary as the cache.\n

\n\n\n

Blitz

\n Note: most of this section is lifted from old documentation. It should be\npretty accurate, but there may be a few discrepancies.\n

\nweave.blitz() compiles Numeric Python expressions for fast \nexecution. For most applications, compiled expressions should provide a \nfactor of 2-10 speed-up over Numeric arrays. Using compiled \nexpressions is meant to be as unobtrusive as possible and works much like \npythons exec statement. As an example, the following code fragment takes a 5 \npoint average of the 512x512 2d image, b, and stores it in array, a:\n\n

\n    from scipy import *  # or from Numeric import *\n    a = ones((512,512), Float64) \n    b = ones((512,512), Float64) \n    # ...do some stuff to fill in b...\n    # now average\n    a[1:-1,1:-1] =  (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1] \\\n                   + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n    
\n \nTo compile the expression, convert the expression to a string by putting\nquotes around it and then use weave.blitz:\n\n
\n    import weave\n    expr = \"a[1:-1,1:-1] =  (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n                          \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n    weave.blitz(expr)\n    
\n\nThe first time weave.blitz is run for a given expression and \nset of arguements, C++ code that accomplishes the exact same task as the Python \nexpression is generated and compiled to an extension module. This can take up \nto a couple of minutes depending on the complexity of the function. Subsequent \ncalls to the function are very fast. Futher, the generated module is saved \nbetween program executions so that the compilation is only done once for a \ngiven expression and associated set of array types. If the given expression\nis executed with a new set of array types, the code most be compiled again. This\ndoes not overwrite the previously compiled function -- both of them are saved and\navailable for exectution. \n

\nThe following table compares the run times for standard Numeric code and \ncompiled code for the 5 point averaging.\n

\n

\n\n\n\n\n\n
Method Run Time (seconds)
Standard Numeric 0.46349
blitz (1st time compiling) 78.95526
blitz (subsequent calls) 0.05843 (factor of 8 speedup)
\n
\n

\nThese numbers are for a 512x512 double precision image run on a 400 MHz Celeron \nprocessor under RedHat Linux 6.2.\n

\nBecause of the slow compile times, its probably most effective to develop \nalgorithms as you usually do using the capabilities of scipy or the Numeric \nmodule. Once the algorithm is perfected, put quotes around it and execute it \nusing weave.blitz. This provides the standard rapid \nprototyping strengths of Python and results in algorithms that run close to \nthat of hand coded C or Fortran.\n\n\n

Requirements

\n\nCurrently, the weave.blitz has only been tested under Linux \nwith gcc-2.95-3 and on Windows with Mingw32 (2.95.2). Its compiler \nrequirements are pretty heavy duty (see the \nblitz++ home page), so it won't \nwork with just any compiler. Particularly MSVC++ isn't up to snuff. A number \nof other compilers such as KAI++ will also work, but my suspicions are that gcc \nwill get the most use.\n\n\n

Limitations

\n
    \n
  1. \nCurrently, weave.blitz handles all standard mathematic \noperators except for the ** power operator. The built-in trigonmetric, log, \nfloor/ceil, and fabs functions might work (but haven't been tested). It also \nhandles all types of array indexing supported by the Numeric module. \n

    \nweave.blitz does not currently support operations that use \narray broadcasting, nor have any of the special purpose functions in Numeric \nsuch as take, compress, etc. been implemented. Note that there are no obvious \nreasons why most of this functionality cannot be added to scipy.weave, so it \nwill likely trickle into future versions. Using slice() objects \ndirectly instead of start:stop:step is also not supported.\n

  2. \n
  3. \nCurrently Python only works on expressions that include assignment such as\n \n
    \n    >>> result = b + c + d\n    
    \n\nThis means that the result array must exist before calling \nweave.blitz. Future versions will allow the following:\n\n
    \n    >>> result = weave.blitz_eval(\"b + c + d\")\n    
    \n
  4. \n
  5. \nweave.blitz works best when algorithms can be expressed in a \n\"vectorized\" form. Algorithms that have a large number of if/thens and other \nconditions are better hand written in C or Fortran. Further, the restrictions \nimposed by requiring vectorized expressions sometimes preclude the use of more \nefficient data structures or algorithms. For maximum speed in these cases, \nhand-coded C or Fortran code is the only way to go.\n
  6. \n
  7. \nweave.blitz can produce different results than Numeric in certain \nsituations. It can happen when the array receiving the results of a \ncalculation is also used during the calculation. The Numeric behavior is to \ncarry out the entire calculation on the right hand side of an equation and \nstore it in a temporary array. This temprorary array is assigned to the array \non the left hand side of the equation. blitz, on the other hand, does a \n\"running\" calculation of the array elements assigning values from the right hand\nside to the elements on the left hand side immediately after they are calculated.\nHere is an example, provided by Prabhu Ramachandran, where this happens:\n\n
    \n        # 4 point average.\n        >>> expr = \"u[1:-1, 1:-1] = (u[0:-2, 1:-1] + u[2:, 1:-1] + \"\\\n        ...                \"u[1:-1,0:-2] + u[1:-1, 2:])*0.25\"\n        >>> u = zeros((5, 5), 'd'); u[0,:] = 100\n        >>> exec (expr)\n        >>> u\n        array([[ 100.,  100.,  100.,  100.,  100.],\n               [   0.,   25.,   25.,   25.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.]])\n        \n        >>> u = zeros((5, 5), 'd'); u[0,:] = 100\n        >>> weave.blitz (expr)\n        >>> u\n        array([[ 100.  ,  100.       ,  100.       ,  100.       ,  100. ],\n               [   0.  ,   25.       ,   31.25     ,   32.8125   ,    0. ],\n               [   0.  ,    6.25     ,    9.375    ,   10.546875 ,    0. ],\n               [   0.  ,    1.5625   ,    2.734375 ,    3.3203125,    0. ],\n               [   0.  ,    0.       ,    0.       ,    0.       ,    0. ]])    \n        
    \n \n You can prevent this behavior by using a temporary array.\n \n
    \n        >>> u = zeros((5, 5), 'd'); u[0,:] = 100\n        >>> temp = zeros((4, 4), 'd');\n        >>> expr = \"temp = (u[0:-2, 1:-1] + u[2:, 1:-1] + \"\\\n        ...        \"u[1:-1,0:-2] + u[1:-1, 2:])*0.25;\"\\\n        ...        \"u[1:-1,1:-1] = temp\"\n        >>> weave.blitz (expr)\n        >>> u\n        array([[ 100.,  100.,  100.,  100.,  100.],\n               [   0.,   25.,   25.,   25.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.],\n               [   0.,    0.,    0.,    0.,    0.]])\n        
    \n \n
  8. \n
  9. \nOne other point deserves mention lest people be confused. \nweave.blitz is not a general purpose Python->C compiler. It \nonly works for expressions that contain Numeric arrays and/or \nPython scalar values. This focused scope concentrates effort on the \ncompuationally intensive regions of the program and sidesteps the difficult \nissues associated with a general purpose Python->C compiler.\n
  10. \n
\n\n\n

Numeric efficiency issues: What compilation buys you

\n\nSome might wonder why compiling Numeric expressions to C++ is beneficial since \noperations on Numeric array operations are already executed within C loops. \nThe problem is that anything other than the simplest expression are executed in \nless than optimal fashion. Consider the following Numeric expression:\n\n
\n    a = 1.2 * b + c * d\n    
\n \nWhen Numeric calculates the value for the 2d array, a, it does \nthe following steps:\n\n
\n    temp1 = 1.2 * b\n    temp2 = c * d\n    a = temp1 + temp2\n    
\n \nTwo things to note. Since c is an (perhaps large) array, a large \ntemporary array must be created to store the results of 1.2 * b. \nThe same is true for temp2. Allocation is slow. The second thing \nis that we have 3 loops executing, one to calculate temp1, one for \ntemp2 and one for adding them up. A C loop for the same problem \nmight look like:\n\n
\n    for(int i = 0; i < M; i++)\n        for(int j = 0; j < N; j++)\n            a[i,j] = 1.2 * b[i,j] + c[i,j] * d[i,j]\n    
\n \nHere, the 3 loops have been fused into a single loop and there is no longer\na need for a temporary array. This provides a significant speed improvement\nover the above example (write me and tell me what you get). \n

\nSo, converting Numeric expressions into C/C++ loops that fuse the loops and \neliminate temporary arrays can provide big gains. The goal then,is to convert \nNumeric expression to C/C++ loops, compile them in an extension module, and \nthen call the compiled extension function. The good news is that there is an \nobvious correspondence between the Numeric expression above and the C loop. The \nbad news is that Numeric is generally much more powerful than this simple \nexample illustrates and handling all possible indexing possibilities results in \nloops that are less than straight forward to write. (take a peak in Numeric for \nconfirmation). Luckily, there are several available tools that simplify the \nprocess.\n\n\n

The Tools

\n\nweave.blitz relies heavily on several remarkable tools. On the \nPython side, the main facilitators are Jermey Hylton's parser module and Jim \nHuginin's Numeric module. On the compiled language side, Todd Veldhuizen's \nblitz++ array library, written in C++ (shhhh. don't tell David Beazley), does \nthe heavy lifting. Don't assume that, because it's C++, it's much slower than C \nor Fortran. Blitz++ uses a jaw dropping array of template techniques \n(metaprogramming, template expression, etc) to convert innocent looking and \nreadable C++ expressions into to code that usually executes within a few \npercentage points of Fortran code for the same problem. This is good. \nUnfortunately all the template raz-ma-taz is very expensive to compile, so the \n200 line extension modules often take 2 or more minutes to compile. This isn't so \ngood. weave.blitz works to minimize this issue by remembering \nwhere compiled modules live and reusing them instead of re-compiling every time \na program is re-run.\n\n\n

Parser

\nTearing Numeric expressions apart, examining the pieces, and then rebuilding \nthem as C++ (blitz) expressions requires a parser of some sort. I can imagine \nsomeone attacking this problem with regular expressions, but it'd likely be \nugly and fragile. Amazingly, Python solves this problem for us. It actually \nexposes its parsing engine to the world through the parser module. \nThe following fragment creates an Abstract Syntax Tree (AST) object for the \nexpression and then converts to a (rather unpleasant looking) deeply nested list \nrepresentation of the tree. \n \n
\n    >>> import parser\n    >>> import scipy.weave.misc\n    >>> ast = parser.suite(\"a = b * c + d\")\n    >>> ast_list = ast.tolist()\n    >>> sym_list = scipy.weave.misc.translate_symbols(ast_list)\n    >>> pprint.pprint(sym_list)\n    ['file_input',\n     ['stmt',\n      ['simple_stmt',\n       ['small_stmt',\n        ['expr_stmt',\n         ['testlist',\n          ['test',\n           ['and_test',\n            ['not_test',\n             ['comparison',\n              ['expr',\n               ['xor_expr',\n                ['and_expr',\n                 ['shift_expr',\n                  ['arith_expr',\n                   ['term',\n                    ['factor', ['power', ['atom', ['NAME', 'a']]]]]]]]]]]]]]],\n         ['EQUAL', '='],\n         ['testlist',\n          ['test',\n           ['and_test',\n            ['not_test',\n             ['comparison',\n              ['expr',\n               ['xor_expr',\n                ['and_expr',\n                 ['shift_expr',\n                  ['arith_expr',\n                   ['term',\n                    ['factor', ['power', ['atom', ['NAME', 'b']]]],\n                    ['STAR', '*'],\n                    ['factor', ['power', ['atom', ['NAME', 'c']]]]],\n                   ['PLUS', '+'],\n                   ['term',\n                    ['factor', ['power', ['atom', ['NAME', 'd']]]]]]]]]]]]]]]]],\n       ['NEWLINE', '']]],\n     ['ENDMARKER', '']]\n    
\n\nDespite its looks, with some tools developed by Jermey H., its possible\nto search these trees for specific patterns (sub-trees), extract the \nsub-tree, manipulate them converting python specific code fragments\nto blitz code fragments, and then re-insert it in the parse tree. The parser\nmodule documentation has some details on how to do this. Traversing the \nnew blitzified tree, writing out the terminal symbols as you go, creates\nour new blitz++ expression string.\n\n \n

Blitz and Numeric

\nThe other nice discovery in the project is that the data structure used\nfor Numeric arrays and blitz arrays is nearly identical. Numeric stores\n\"strides\" as byte offsets and blitz stores them as element offsets, but\nother than that, they are the same. Further, most of the concept and\ncapabilities of the two libraries are remarkably similar. It is satisfying \nthat two completely different implementations solved the problem with \nsimilar basic architectures. It is also fortitous. The work involved in \nconverting Numeric expressions to blitz expressions was greatly diminished.\nAs an example, consider the code for slicing an array in Python with a\nstride:\n\n
\n    >>> a = b[0:4:2] + c\n    >>> a\n    [0,2,4]\n    
\n\n\nIn Blitz it is as follows:\n\n
\n    Array<2,int> b(10);\n    Array<2,int> c(3);\n    // ...\n    Array<2,int> a = b(Range(0,3,2)) + c;\n    
\n\n\nHere the range object works exactly like Python slice objects with the exception\nthat the top index (3) is inclusive where as Python's (4) is exclusive. Other \ndifferences include the type declaraions in C++ and parentheses instead of \nbrackets for indexing arrays. Currently, weave.blitz handles the \ninclusive/exclusive issue by subtracting one from upper indices during the\ntranslation. An alternative that is likely more robust/maintainable in the \nlong run, is to write a PyRange class that behaves like Python's range. \nThis is likely very easy.\n

\nThe stock blitz also doesn't handle negative indices in ranges. The current \nimplementation of the blitz() has a partial solution to this \nproblem. It calculates and index that starts with a '-' sign by subtracting it \nfrom the maximum index in the array so that:\n\n

\n                    upper index limit\n                        /-----\\\n    b[:-1] -> b(Range(0,Nb[0]-1-1))\n    
\n\nThis approach fails, however, when the top index is calculated from other \nvalues. In the following scenario, if i+j evaluates to a negative \nvalue, the compiled code will produce incorrect results and could even core-\ndump. Right now, all calculated indices are assumed to be positive.\n \n
\n    b[:i-j] -> b(Range(0,i+j))\n    
\n\nA solution is to calculate all indices up front using if/then to handle the\n+/- cases. This is a little work and results in more code, so it hasn't been\ndone. I'm holding out to see if blitz++ can be modified to handle negative\nindexing, but haven't looked into how much effort is involved yet. While it \nneeds fixin', I don't think there is a ton of code where this is an issue.\n

\nThe actual translation of the Python expressions to blitz expressions is \ncurrently a two part process. First, all x:y:z slicing expression are removed\nfrom the AST, converted to slice(x,y,z) and re-inserted into the tree. Any\nmath needed on these expressions (subtracting from the \nmaximum index, etc.) are also preformed here. _beg and _end are used as special\nvariables that are defined as blitz::fromBegin and blitz::toEnd.\n\n

\n    a[i+j:i+j+1,:] = b[2:3,:] \n    
\n\nbecomes a more verbose:\n \n
\n    a[slice(i+j,i+j+1),slice(_beg,_end)] = b[slice(2,3),slice(_beg,_end)]\n    
\n \nThe second part does a simple string search/replace to convert to a blitz \nexpression with the following translations:\n\n
\n    slice(_beg,_end) -> _all  # not strictly needed, but cuts down on code.\n    slice            -> blitz::Range\n    [                -> (\n    ]                -> )\n    _stp             -> 1\n    
\n\n_all is defined in the compiled function as \nblitz::Range.all(). These translations could of course happen \ndirectly in the syntax tree. But the string replacement is slightly easier. \nNote that name spaces are maintained in the C++ code to lessen the likelyhood \nof name clashes. Currently no effort is made to detect name clashes. A good \nrule of thumb is don't use values that start with '_' or 'py_' in compiled \nexpressions and you'll be fine.\n\n \n

Type definitions and coersion

\n\nSo far we've glossed over the dynamic vs. static typing issue between Python \nand C++. In Python, the type of value that a variable holds can change\nthrough the course of program execution. C/C++, on the other hand, forces you\nto declare the type of value a variables will hold prior at compile time.\nweave.blitz handles this issue by examining the types of the\nvariables in the expression being executed, and compiling a function for those\nexplicit types. For example:\n\n
\n    a = ones((5,5),Float32)\n    b = ones((5,5),Float32)\n    weave.blitz(\"a = a + b\")\n    
\n\nWhen compiling this expression to C++, weave.blitz sees that the\nvalues for a and b in the local scope have type Float32, or 'float'\non a 32 bit architecture. As a result, it compiles the function using \nthe float type (no attempt has been made to deal with 64 bit issues).\nIt also goes one step further. If all arrays have the same type, a templated\nversion of the function is made and instantiated for float, double, \ncomplex, and complex arrays. Note: This feature has been \nremoved from the current version of the code. Each version will be compiled\nseparately \n

\nWhat happens if you call a compiled function with array types that are \ndifferent than the ones for which it was originally compiled? No biggie, you'll \njust have to wait on it to compile a new version for your new types. This \ndoesn't overwrite the old functions, as they are still accessible. See the \ncatalog section in the inline() documentation to see how this is handled. \nSuffice to say, the mechanism is transparent to the user and behaves \nlike dynamic typing with the occasional wait for compiling newly typed \nfunctions.\n

\nWhen working with combined scalar/array operations, the type of the array is \nalways used. This is similar to the savespace flag that was recently \nadded to Numeric. This prevents issues with the following expression perhaps \nunexpectedly being calculated at a higher (more expensive) precision that can \noccur in Python:\n\n

\n    >>> a = array((1,2,3),typecode = Float32)\n    >>> b = a * 2.1 # results in b being a Float64 array.\n    
\n \nIn this example, \n\n
\n    >>> a = ones((5,5),Float32)\n    >>> b = ones((5,5),Float32)\n    >>> weave.blitz(\"b = a * 2.1\")\n    
\n \nthe 2.1 is cast down to a float before carrying out \nthe operation. If you really want to force the calculation to be a \ndouble, define a and b as \ndouble arrays.\n

\nOne other point of note. Currently, you must include both the right hand side \nand left hand side (assignment side) of your equation in the compiled \nexpression. Also, the array being assigned to must be created prior to calling \nweave.blitz. I'm pretty sure this is easily changed so that a \ncompiled_eval expression can be defined, but no effort has been made to \nallocate new arrays (and decern their type) on the fly.\n\n \n

Cataloging Compiled Functions

\n\nSee the Cataloging functions section in the \nweave.inline() documentation.\n\n \n

Checking Array Sizes

\n\nSurprisingly, one of the big initial problems with compiled code was making\nsure all the arrays in an operation were of compatible type. The following\ncase is trivially easy:\n\n
\n    a = b + c\n    
\n \nIt only requires that arrays a, b, and c \nhave the same shape. However, expressions like:\n\n
\n    a[i+j:i+j+1,:] = b[2:3,:] + c\n    
\n\nare not so trivial. Since slicing is involved, the size of the slices, not the \ninput arrays must be checked. Broadcasting complicates things further because \narrays and slices with different dimensions and shapes may be compatible for \nmath operations (broadcasting isn't yet supported by \nweave.blitz). Reductions have a similar effect as their \nresults are different shapes than their input operand. The binary operators in \nNumeric compare the shapes of their two operands just before they operate on \nthem. This is possible because Numeric treats each operation independently. \nThe intermediate (temporary) arrays created during sub-operations in an \nexpression are tested for the correct shape before they are combined by another \noperation. Because weave.blitz fuses all operations into a \nsingle loop, this isn't possible. The shape comparisons must be done and \nguaranteed compatible before evaluating the expression.\n

\nThe solution chosen converts input arrays to \"dummy arrays\" that only represent \nthe dimensions of the arrays, not the data. Binary operations on dummy arrays \ncheck that input array sizes are comptible and return a dummy array with the \nsize correct size. Evaluating an expression of dummy arrays traces the \nchanging array sizes through all operations and fails if incompatible array \nsizes are ever found. \n

\nThe machinery for this is housed in weave.size_check. It \nbasically involves writing a new class (dummy array) and overloading it math \noperators to calculate the new sizes correctly. All the code is in Python and \nthere is a fair amount of logic (mainly to handle indexing and slicing) so the \noperation does impose some overhead. For large arrays (ie. 50x50x50), the \noverhead is negligible compared to evaluating the actual expression. For small \narrays (ie. 16x16), the overhead imposed for checking the shapes with this \nmethod can cause the weave.blitz to be slower than evaluating \nthe expression in Python. \n

\nWhat can be done to reduce the overhead? (1) The size checking code could be \nmoved into C. This would likely remove most of the overhead penalty compared \nto Numeric (although there is also some calling overhead), but no effort has \nbeen made to do this. (2) You can also call weave.blitz with\ncheck_size=0 and the size checking isn't done. However, if the \nsizes aren't compatible, it can cause a core-dump. So, foregoing size_checking\nisn't advisable until your code is well debugged.\n\n \n

Creating the Extension Module

\n\nweave.blitz uses the same machinery as \nweave.inline to build the extension module. The only difference\nis the code included in the function is automatically generated from the\nNumeric array expression instead of supplied by the user.\n\n\n

Extension Modules

\nweave.inline and weave.blitz are high level tools\nthat generate extension modules automatically. Under the covers, they use several\nclasses from weave.ext_tools to help generate the extension module.\nThe main two classes are ext_module and ext_function (I'd\nlike to add ext_class and ext_method also). These classes\nsimplify the process of generating extension modules by handling most of the \"boiler\nplate\" code automatically.\n\n\nNote: inline actually sub-classes weave.ext_tools.ext_function \nto generate slightly different code than the standard ext_function.\nThe main difference is that the standard class converts function arguments to\nC types, while inline always has two arguments, the local and global dicts, and\nthe grabs the variables that need to be convereted to C from these.\n\n\n\n

A Simple Example

\nThe following simple example demonstrates how to build an extension module within\na Python function:\n\n
\n    # examples/increment_example.py\n    from weave import ext_tools\n    \n    def build_increment_ext():\n        \"\"\" Build a simple extension with functions that increment numbers.\n            The extension will be built in the local directory.\n        \"\"\"        \n        mod = ext_tools.ext_module('increment_ext')\n    \n        a = 1 # effectively a type declaration for 'a' in the \n              # following functions.\n    \n        ext_code = \"return_val = Py::new_reference_to(Py::Int(a+1));\"    \n        func = ext_tools.ext_function('increment',ext_code,['a'])\n        mod.add_function(func)\n        \n        ext_code = \"return_val = Py::new_reference_to(Py::Int(a+2));\"    \n        func = ext_tools.ext_function('increment_by_2',ext_code,['a'])\n        mod.add_function(func)\n                \n        mod.compile()\n    
\n\n\nThe function build_increment_ext() creates an extension module \nnamed increment_ext and compiles it to a shared library (.so or \n.pyd) that can be loaded into Python.. increment_ext contains two \nfunctions, increment and increment_by_2. \n\nThe first line of build_increment_ext(),\n\n
\n        mod = ext_tools.ext_module('increment_ext') \n    
\n\ncreates an ext_module instance that is ready to have \next_function instances added to it. ext_function \ninstances are created much with a calling convention similar to \nweave.inline(). The most common call includes a C/C++ code \nsnippet and a list of the arguments for the function. The following\n\n
\n        ext_code = \"return_val = Py::new_reference_to(Py::Int(a+1));\"    \n        func = ext_tools.ext_function('increment',ext_code,['a'])\n    
\n \ncreates a C/C++ extension function that is equivalent to the following Python\nfunction:\n\n
\n        def increment(a):\n            return a + 1\n    
\n\nA second method is also added to the module and then,\n\n
\n        mod.compile()\n    
\n\nis called to build the extension module. By default, the module is created\nin the current working directory.\n\nThis example is available in the examples/increment_example.py file\nfound in the weave directory. At the bottom of the file in the\nmodule's \"main\" program, an attempt to import increment_ext without\nbuilding it is made. If this fails (the module doesn't exist in the PYTHONPATH), \nthe module is built by calling build_increment_ext(). This approach\nonly takes the time consuming ( a few seconds for this example) process of building\nthe module if it hasn't been built before.\n\n
\n    if __name__ == \"__main__\":\n        try:\n            import increment_ext\n        except ImportError:\n            build_increment_ext()\n            import increment_ext\n        a = 1\n        print 'a, a+1:', a, increment_ext.increment(a)\n        print 'a, a+2:', a, increment_ext.increment_by_2(a)           \n    
\n\n\nNote: If we were willing to always pay the penalty of building the C++ code for \na module, we could store the md5 checksum of the C++ code along with some \ninformation about the compiler, platform, etc. Then, \next_module.compile() could try importing the module before it actually\ncompiles it, check the md5 checksum and other meta-data in the imported module\nwith the meta-data of the code it just produced and only compile the code if\nthe module didn't exist or the meta-data didn't match. This would reduce the\nabove code to:\n\n
\n    if __name__ == \"__main__\":\n        build_increment_ext()\n\n        a = 1\n        print 'a, a+1:', a, increment_ext.increment(a)\n        print 'a, a+2:', a, increment_ext.increment_by_2(a)           \n    
\n\nNote: There would always be the overhead of building the C++ code, but it would only actually compile the code once. You pay a little in overhead and get cleaner\n\"import\" code. Needs some thought.\n\n

\n\nIf you run increment_example.py from the command line, you get\nthe following:\n\n

\n    [eric@n0]$ python increment_example.py\n    a, a+1: 1 2\n    a, a+2: 1 3\n    
\n\nIf the module didn't exist before it was run, the module is created. If it did\nexist, it is just imported and used.\n\n\n

Fibonacci Example

\nexamples/fibonacci.py provides a little more complex example of \nhow to use ext_tools. Fibonacci numbers are a series of numbers \nwhere each number in the series is the sum of the previous two: 1, 1, 2, 3, 5, \n8, etc. Here, the first two numbers in the series are taken to be 1. One \napproach to calculating Fibonacci numbers uses recursive function calls. In \nPython, it might be written as:\n\n
\n    def fib(a):\n        if a <= 2:\n            return 1\n        else:\n            return fib(a-2) + fib(a-1)\n    
\n\nIn C, the same function would look something like this:\n\n
\n     int fib(int a)\n     {                   \n         if(a <= 2)\n             return 1;\n         else\n             return fib(a-2) + fib(a-1);  \n     }                      \n    
\n\nRecursion is much faster in C than in Python, so it would be beneficial\nto use the C version for fibonacci number calculations instead of the\nPython version. We need an extension function that calls this C function\nto do this. This is possible by including the above code snippet as \n\"support code\" and then calling it from the extension function. Support \ncode snippets (usually structure definitions, helper functions and the like)\nare inserted into the extension module C/C++ file before the extension\nfunction code. Here is how to build the C version of the fibonacci number\ngenerator:\n\n
\ndef build_fibonacci():\n    \"\"\" Builds an extension module with fibonacci calculators.\n    \"\"\"\n    mod = ext_tools.ext_module('fibonacci_ext')\n    a = 1 # this is effectively a type declaration\n    \n    # recursive fibonacci in C \n    fib_code = \"\"\"\n                   int fib1(int a)\n                   {                   \n                       if(a <= 2)\n                           return 1;\n                       else\n                           return fib1(a-2) + fib1(a-1);  \n                   }                         \n               \"\"\"\n    ext_code = \"\"\"\n                   int val = fib1(a);\n                   return_val = Py::new_reference_to(Py::Int(val));\n               \"\"\"    \n    fib = ext_tools.ext_function('fib',ext_code,['a'])\n    fib.customize.add_support_code(fib_code)\n    mod.add_function(fib)\n\n    mod.compile()\n\n    
\n\nXXX More about custom_info, and what xxx_info instances are good for.\n\n

\n\nNote: recursion is not the fastest way to calculate fibonacci numbers, but this \napproach serves nicely for this example.\n\n

\n\n

Customizing Type Conversions -- Type Factories

\nnot written\n\n

Things I wish weave did

\n\nIt is possible to get name clashes if you uses a variable name that is already defined\nin a header automatically included (such as stdio.h) For instance, if you\ntry to pass in a variable named stdout, you'll get a cryptic error report\ndue to the fact that stdio.h also defines the name. weave\nshould probably try and handle this in some way.\n\nOther things...", "methods": [], "methods_before": [], "changed_methods": [], "nloc": null, "complexity": null, "token_count": null, "diff_parsed": { "added": [ "For printing strings, the format statement needs to be changed. Also, weave", "doesn't convert strings to char*. Instead it uses CXX Py::String type, so", "you have to do a little more work. Here we convert it to a C++ std::string", "and then ask cor the char* version.", " >>> a = 'string'", " >>> weave.inline(r'printf(\"%s\\n\",std::string(a).c_str());',['a'])", "

", "", "This is a little convoluted. Perhaps strings should convert to std::string", "objects instead of CXX objects. Or maybe to char*.", "" ], "deleted": [ "For printing strings, the format statement needs to be changed.", " >>> a = 'string'", " >>> weave.inline(r'printf(\"%s\\n\",a);',['a'])" ] } } ] }, { "hash": "c9d6cb8e55c5bd9fc27b359e3f87530b1e602288", "msg": "found improved way of making g++ -shared the linker instead of simply adding stdc++ as a library for gcc.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-16T09:41:21+00:00", "author_timezone": 0, "committer_date": "2002-01-16T09:41:21+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "653df5af033fd2514869639131074f58c68a2f38" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 6, "insertions": 24, "lines": 30, "files": 1, "dmm_unit_size": 1.0, "dmm_unit_complexity": 1.0, "dmm_unit_interfacing": 1.0, "modified_files": [ { "old_path": "weave/build_tools.py", "new_path": "weave/build_tools.py", "filename": "build_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -21,6 +21,21 @@\n import tempfile\n import exceptions\n \n+# If linker is 'gcc', this will convert it to 'g++'\n+# necessary to make sure stdc++ is linked in cross-platform way.\n+import distutils.sysconfig\n+\n+old_init_posix = distutils.sysconfig._init_posix\n+\n+def _init_posix():\n+ old_init_posix()\n+ ld = distutils.sysconfig._config_vars['LDSHARED']\n+ distutils.sysconfig._config_vars['LDSHARED'] = ld.replace('gcc','g++')\n+\n+distutils.sysconfig._init_posix = _init_posix \n+# end force g++\n+\n+\n class CompileError(exceptions.Exception):\n pass\n \n@@ -144,12 +159,15 @@ def build_extension(module_path,compiler_name = '',build_dir = None,\n sources = kw.get('sources',[])\n kw['sources'] = [module_path] + sources \n \n- # add module to the needed source code files and build extension\n- # FIX this is g++ specific. It probably should be fixed for other\n- # Unices/compilers. Find a generic solution\n- if compiler_name != 'msvc':\n- libraries = kw.get('libraries',[])\n- kw['libraries'] = ['stdc++'] + libraries \n+ # ! This was fixed at beginning of file by using g++ on most \n+ # !machines. We'll have to check how to handle it on non-gcc machines \n+ ## add module to the needed source code files and build extension\n+ ## FIX this is g++ specific. It probably should be fixed for other\n+ ## Unices/compilers. Find a generic solution\n+ #if compiler_name != 'msvc':\n+ # libraries = kw.get('libraries',[])\n+ # kw['libraries'] = ['stdc++'] + libraries \n+ # !\n \n # SunOS specific\n # fix for issue with linking to libstdc++.a. see:\n", "added_lines": 24, "deleted_lines": 6, "source_code": "\"\"\" Tools for compiling C/C++ code to extension modules\n\n The main function, build_extension(), takes the C/C++ file\n along with some other options and builds a Python extension.\n It uses distutils for most of the heavy lifting.\n \n choose_compiler() is also useful (mainly on windows anyway)\n for trying to determine whether MSVC++ or gcc is available.\n MSVC doesn't handle templates as well, so some of the code emitted\n by the python->C conversions need this info to choose what kind\n of code to create.\n \n The other main thing here is an alternative version of the MingW32\n compiler class. The class makes it possible to build libraries with\n gcc even if the original version of python was built using MSVC. It\n does this by converting a pythonxx.lib file to a libpythonxx.a file.\n Note that you need write access to the pythonxx/lib directory to do this.\n\"\"\"\n\nimport sys,os,string,time\nimport tempfile\nimport exceptions\n\n# If linker is 'gcc', this will convert it to 'g++'\n# necessary to make sure stdc++ is linked in cross-platform way.\nimport distutils.sysconfig\n\nold_init_posix = distutils.sysconfig._init_posix\n\ndef _init_posix():\n old_init_posix()\n ld = distutils.sysconfig._config_vars['LDSHARED']\n distutils.sysconfig._config_vars['LDSHARED'] = ld.replace('gcc','g++')\n\ndistutils.sysconfig._init_posix = _init_posix \n# end force g++\n\n\nclass CompileError(exceptions.Exception):\n pass\n \ndef build_extension(module_path,compiler_name = '',build_dir = None,\n temp_dir = None, verbose = 0, **kw):\n \"\"\" Build the file given by module_path into a Python extension module.\n \n build_extensions uses distutils to build Python extension modules.\n kw arguments not used are passed on to the distutils extension\n module. Directory settings can handle absoulte settings, but don't\n currently expand '~' or environment variables.\n \n module_path -- the full path name to the c file to compile. \n Something like: /full/path/name/module_name.c \n The name of the c/c++ file should be the same as the\n name of the module (i.e. the initmodule() routine)\n compiler_name -- The name of the compiler to use. On Windows if it \n isn't given, MSVC is used if it exists (is found).\n gcc is used as a second choice. If neither are found, \n the default distutils compiler is used. Acceptable \n names are 'gcc', 'msvc' or any of the compiler names \n shown by distutils.ccompiler.show_compilers()\n build_dir -- The location where the resulting extension module \n should be placed. This location must be writable. If\n it isn't, several default locations are tried. If the \n build_dir is not in the current python path, a warning\n is emitted, and it is added to the end of the path.\n build_dir defaults to the current directory.\n temp_dir -- The location where temporary files (*.o or *.obj)\n from the build are placed. This location must be \n writable. If it isn't, several default locations are \n tried. It defaults to tempfile.gettempdir()\n verbose -- 0, 1, or 2. 0 is as quiet as possible. 1 prints\n minimal information. 2 is noisy. \n **kw -- keyword arguments. These are passed on to the \n distutils extension module. Most of the keywords\n are listed below.\n\n Distutils keywords. These are cut and pasted from Greg Ward's\n distutils.extension.Extension class for convenience:\n \n sources : [string]\n list of source filenames, relative to the distribution root\n (where the setup script lives), in Unix form (slash-separated)\n for portability. Source files may be C, C++, SWIG (.i),\n platform-specific resource files, or whatever else is recognized\n by the \"build_ext\" command as source for a Python extension.\n Note: The module_path file is always appended to the front of this\n list \n include_dirs : [string]\n list of directories to search for C/C++ header files (in Unix\n form for portability) \n define_macros : [(name : string, value : string|None)]\n list of macros to define; each macro is defined using a 2-tuple,\n where 'value' is either the string to define it to or None to\n define it without a particular value (equivalent of \"#define\n FOO\" in source or -DFOO on Unix C compiler command line) \n undef_macros : [string]\n list of macros to undefine explicitly\n library_dirs : [string]\n list of directories to search for C/C++ libraries at link time\n libraries : [string]\n list of library names (not filenames or paths) to link against\n runtime_library_dirs : [string]\n list of directories to search for C/C++ libraries at run time\n (for shared extensions, this is when the extension is loaded)\n extra_objects : [string]\n list of extra files to link with (eg. object files not implied\n by 'sources', static library that must be explicitly specified,\n binary resource files, etc.)\n extra_compile_args : [string]\n any extra platform- and compiler-specific information to use\n when compiling the source files in 'sources'. For platforms and\n compilers where \"command line\" makes sense, this is typically a\n list of command-line arguments, but for other platforms it could\n be anything.\n extra_link_args : [string]\n any extra platform- and compiler-specific information to use\n when linking object files together to create the extension (or\n to create a new static Python interpreter). Similar\n interpretation as for 'extra_compile_args'.\n export_symbols : [string]\n list of symbols to be exported from a shared extension. Not\n used on all platforms, and not generally necessary for Python\n extensions, which typically export exactly one symbol: \"init\" +\n extension_name.\n \"\"\"\n success = 0\n from distutils.core import setup, Extension\n \n # this is a screwy trick to get rid of a ton of warnings on Unix\n import distutils.sysconfig\n distutils.sysconfig.get_config_vars()\n if distutils.sysconfig._config_vars.has_key('OPT'):\n flags = distutils.sysconfig._config_vars['OPT'] \n flags = flags.replace('-Wall','')\n distutils.sysconfig._config_vars['OPT'] = flags\n \n # get the name of the module and the extension directory it lives in. \n module_dir,cpp_name = os.path.split(os.path.abspath(module_path))\n module_name,ext = os.path.splitext(cpp_name) \n \n # configure temp and build directories\n temp_dir = configure_temp_dir(temp_dir) \n build_dir = configure_build_dir(module_dir)\n \n compiler_name = choose_compiler(compiler_name)\n configure_sys_argv(compiler_name,temp_dir,build_dir)\n \n # the business end of the function\n try:\n if verbose == 1:\n print 'Compiling code...'\n \n # set compiler verboseness 2 or more makes it output results\n if verbose > 1: verb = 1 \n else: verb = 0\n \n t1 = time.time() \n # add module to the needed source code files and build extension\n sources = kw.get('sources',[])\n kw['sources'] = [module_path] + sources \n \n # ! This was fixed at beginning of file by using g++ on most \n # !machines. We'll have to check how to handle it on non-gcc machines \n ## add module to the needed source code files and build extension\n ## FIX this is g++ specific. It probably should be fixed for other\n ## Unices/compilers. Find a generic solution\n #if compiler_name != 'msvc':\n # libraries = kw.get('libraries',[])\n # kw['libraries'] = ['stdc++'] + libraries \n # !\n \n # SunOS specific\n # fix for issue with linking to libstdc++.a. see:\n # http://mail.python.org/pipermail/python-dev/2001-March/013510.html\n platform = sys.platform\n version = sys.version.lower()\n if platform[:5] == 'sunos' and version.find('gcc') != -1:\n extra_link_args = kw.get('extra_link_args',[])\n kw['extra_link_args'] = ['-mimpure-text'] + extra_link_args\n \n ext = Extension(module_name, **kw)\n \n # the switcheroo on SystemExit here is meant to keep command line\n # sessions from exiting when compiles fail.\n builtin = sys.modules['__builtin__']\n old_SysExit = builtin.__dict__['SystemExit']\n builtin.__dict__['SystemExit'] = CompileError\n \n # distutils for MSVC messes with the environment, so we save the\n # current state and restore them afterward.\n import copy\n environ = copy.deepcopy(os.environ)\n try:\n setup(name = module_name, ext_modules = [ext],verbose=verb)\n finally:\n # restore state\n os.environ = environ \n # restore SystemExit\n builtin.__dict__['SystemExit'] = old_SysExit\n t2 = time.time()\n \n if verbose == 1:\n print 'finished compiling (sec): ', t2 - t1 \n success = 1\n configure_python_path(build_dir)\n except SyntaxError: #TypeError:\n success = 0 \n \n # restore argv after our trick... \n restore_sys_argv()\n \n return success\n\nold_argv = []\ndef configure_sys_argv(compiler_name,temp_dir,build_dir):\n # We're gonna play some tricks with argv here to pass info to distutils \n # which is really built for command line use. better way??\n global old_argv\n old_argv = sys.argv[:] \n sys.argv = ['','build_ext','--build-lib', build_dir,\n '--build-temp',temp_dir] \n if compiler_name == 'gcc':\n sys.argv.insert(2,'--compiler='+compiler_name)\n elif compiler_name:\n sys.argv.insert(2,'--compiler='+compiler_name)\n\ndef restore_sys_argv():\n sys.argv = old_argv\n \ndef configure_python_path(build_dir): \n #make sure the module lives in a directory on the python path.\n python_paths = [os.path.abspath(x) for x in sys.path]\n if os.path.abspath(build_dir) not in python_paths:\n #print \"warning: build directory was not part of python path.\"\\\n # \" It has been appended to the path.\"\n sys.path.append(os.path.abspath(build_dir))\n\ndef choose_compiler(compiler_name=''):\n \"\"\" Try and figure out which compiler is gonna be used on windows.\n On other platforms, it just returns whatever value it is given.\n \n converts 'gcc' to 'mingw32' on win32\n \"\"\"\n if sys.platform == 'win32': \n if not compiler_name:\n # On Windows, default to MSVC and use gcc if it wasn't found\n # wasn't found. If neither are found, go with whatever\n # the default is for distutils -- and probably fail...\n if msvc_exists():\n compiler_name = 'msvc'\n elif gcc_exists():\n compiler_name = 'mingw32'\n elif compiler_name == 'gcc':\n compiler_name = 'mingw32'\n else:\n # don't know how to force gcc -- look into this.\n if compiler_name == 'gcc':\n compiler_name = 'unix' \n return compiler_name\n \ndef gcc_exists():\n \"\"\" Test to make sure gcc is found \n \n Does this return correct value on win98???\n \"\"\"\n result = 0\n try:\n w,r=os.popen4('gcc -v')\n w.close()\n str_result = r.read()\n #print str_result\n if string.find(str_result,'Reading specs') != -1:\n result = 1\n except:\n # This was needed because the msvc compiler messes with\n # the path variable. and will occasionlly mess things up\n # so much that gcc is lost in the path. (Occurs in test\n # scripts)\n result = not os.system('gcc -v')\n return result\n\ndef msvc_exists():\n \"\"\" Determine whether MSVC is available on the machine.\n \"\"\"\n result = 0\n try:\n w,r=os.popen4('cl')\n w.close()\n str_result = r.read()\n #print str_result\n if string.find(str_result,'Microsoft') != -1:\n result = 1\n except:\n #assume we're ok if devstudio exists\n import distutils.msvccompiler\n version = distutils.msvccompiler.get_devstudio_version()\n if version:\n result = 1\n return result\n\ndef configure_temp_dir(temp_dir=None):\n if temp_dir is None: \n temp_dir = tempfile.gettempdir()\n elif not os.path.exists(temp_dir) or not os.access(temp_dir,os.W_OK):\n print \"warning: specified temp_dir '%s' does not exist or is \" \\\n \"or is not writable. Using the default temp directory\" % \\\n temp_dir\n temp_dir = tempfile.gettempdir()\n\n # final check that that directories are writable. \n if not os.access(temp_dir,os.W_OK):\n msg = \"Either the temp or build directory wasn't writable. Check\" \\\n \" these locations: '%s'\" % temp_dir \n raise ValueError, msg\n return temp_dir\n\ndef configure_build_dir(build_dir=None):\n # make sure build_dir exists and is writable\n if build_dir and (not os.path.exists(build_dir) or \n not os.access(build_dir,os.W_OK)):\n print \"warning: specified build_dir '%s' does not exist or is \" \\\n \"or is not writable. Trying default locations\" % build_dir\n build_dir = None\n \n if build_dir is None:\n #default to building in the home directory of the given module. \n build_dir = os.curdir\n # if it doesn't work use the current directory. This should always\n # be writable. \n if not os.access(build_dir,os.W_OK):\n print \"warning:, neither the module's directory nor the \"\\\n \"current directory are writable. Using the temporary\"\\\n \"directory.\"\n build_dir = tempfile.gettempdir()\n\n # final check that that directories are writable.\n if not os.access(build_dir,os.W_OK):\n msg = \"The build directory wasn't writable. Check\" \\\n \" this location: '%s'\" % build_dir\n raise ValueError, msg\n \n return os.path.abspath(build_dir) \n \nif sys.platform == 'win32':\n import distutils.cygwinccompiler\n # the same as cygwin plus some additional parameters\n class Mingw32CCompiler (distutils.cygwinccompiler.CygwinCCompiler):\n \"\"\" A modified MingW32 compiler compatible with an MSVC built Python.\n \n \"\"\"\n \n compiler_type = 'mingw32'\n \n def __init__ (self,\n verbose=0,\n dry_run=0,\n force=0):\n \n distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose, \n dry_run, force)\n \n # A real mingw32 doesn't need to specify a different entry point,\n # but cygwin 2.91.57 in no-cygwin-mode needs it.\n if self.gcc_version <= \"2.91.57\":\n entry_point = '--entry _DllMain@12'\n else:\n entry_point = ''\n if self.linker_dll == 'dllwrap':\n self.linker = 'dllwrap' + ' --driver-name g++'\n elif self.linker_dll == 'gcc':\n self.linker = 'g++' \n # **changes: eric jones 4/11/01\n # 1. Check for import library on Windows. Build if it doesn't exist.\n if not import_library_exists():\n build_import_library()\n \n # **changes: eric jones 4/11/01\n # 2. increased optimization and turned off all warnings\n # 3. also added --driver-name g++\n #self.set_executables(compiler='gcc -mno-cygwin -O2 -w',\n # compiler_so='gcc -mno-cygwin -mdll -O2 -w',\n # linker_exe='gcc -mno-cygwin',\n # linker_so='%s --driver-name g++ -mno-cygwin -mdll -static %s' \n # % (self.linker, entry_point))\n self.set_executables(compiler='g++ -mno-cygwin -O2 -w',\n compiler_so='g++ -mno-cygwin -mdll -O2 -w -Wstrict-prototypes',\n linker_exe='g++ -mno-cygwin',\n linker_so='%s -mno-cygwin -mdll -static %s' \n % (self.linker, entry_point))\n \n # Maybe we should also append -mthreads, but then the finished\n # dlls need another dll (mingwm10.dll see Mingw32 docs)\n # (-mthreads: Support thread-safe exception handling on `Mingw32') \n \n # no additional libraries needed \n self.dll_libraries=[]\n \n # __init__ ()\n \n # On windows platforms, we want to default to mingw32 (gcc)\n # because msvc can't build blitz stuff.\n # We should also check the version of gcc available...\n #distutils.ccompiler._default_compilers['nt'] = 'mingw32'\n #distutils.ccompiler._default_compilers = (('nt', 'mingw32'))\n # reset the Mingw32 compiler in distutils to the one defined above\n distutils.cygwinccompiler.Mingw32CCompiler = Mingw32CCompiler\n \n def import_library_exists():\n \"\"\" on windows platforms, make sure a gcc import library exists\n \"\"\"\n if os.name == 'nt':\n lib_name = \"libpython%d%d.a\" % tuple(sys.version_info[:2])\n full_path = os.path.join(sys.prefix,'libs',lib_name)\n if not os.path.exists(full_path):\n return 0\n return 1\n \n def build_import_library():\n \"\"\" Build the import libraries for Mingw32-gcc on Windows\n \"\"\"\n import lib2def as lib2def\n #libfile, deffile = parse_cmd()\n #if deffile == None:\n # deffile = sys.stdout\n #else:\n # deffile = open(deffile, 'w')\n lib_name = \"python%d%d.lib\" % tuple(sys.version_info[:2]) \n lib_file = os.path.join(sys.prefix,'libs',lib_name)\n def_name = \"python%d%d.def\" % tuple(sys.version_info[:2]) \n def_file = os.path.join(sys.prefix,'libs',def_name)\n nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file)\n nm_output = lib2def.getnm(nm_cmd)\n dlist, flist = lib2def.parse_nm(nm_output)\n lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w'))\n \n out_name = \"libpython%d%d.a\" % tuple(sys.version_info[:2])\n out_file = os.path.join(sys.prefix,'libs',out_name)\n dll_name = \"python%d%d.dll\" % tuple(sys.version_info[:2])\n args = (dll_name,def_file,out_file)\n cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args\n success = not os.system(cmd)\n # for now, fail silently\n if not success:\n print 'WARNING: failed to build import library for gcc. Linking will fail.'\n #if not success:\n # msg = \"Couldn't find import library, and failed to build it.\"\n # raise DistutilsPlatformError, msg\n \ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\n\n\n", "source_code_before": "\"\"\" Tools for compiling C/C++ code to extension modules\n\n The main function, build_extension(), takes the C/C++ file\n along with some other options and builds a Python extension.\n It uses distutils for most of the heavy lifting.\n \n choose_compiler() is also useful (mainly on windows anyway)\n for trying to determine whether MSVC++ or gcc is available.\n MSVC doesn't handle templates as well, so some of the code emitted\n by the python->C conversions need this info to choose what kind\n of code to create.\n \n The other main thing here is an alternative version of the MingW32\n compiler class. The class makes it possible to build libraries with\n gcc even if the original version of python was built using MSVC. It\n does this by converting a pythonxx.lib file to a libpythonxx.a file.\n Note that you need write access to the pythonxx/lib directory to do this.\n\"\"\"\n\nimport sys,os,string,time\nimport tempfile\nimport exceptions\n\nclass CompileError(exceptions.Exception):\n pass\n \ndef build_extension(module_path,compiler_name = '',build_dir = None,\n temp_dir = None, verbose = 0, **kw):\n \"\"\" Build the file given by module_path into a Python extension module.\n \n build_extensions uses distutils to build Python extension modules.\n kw arguments not used are passed on to the distutils extension\n module. Directory settings can handle absoulte settings, but don't\n currently expand '~' or environment variables.\n \n module_path -- the full path name to the c file to compile. \n Something like: /full/path/name/module_name.c \n The name of the c/c++ file should be the same as the\n name of the module (i.e. the initmodule() routine)\n compiler_name -- The name of the compiler to use. On Windows if it \n isn't given, MSVC is used if it exists (is found).\n gcc is used as a second choice. If neither are found, \n the default distutils compiler is used. Acceptable \n names are 'gcc', 'msvc' or any of the compiler names \n shown by distutils.ccompiler.show_compilers()\n build_dir -- The location where the resulting extension module \n should be placed. This location must be writable. If\n it isn't, several default locations are tried. If the \n build_dir is not in the current python path, a warning\n is emitted, and it is added to the end of the path.\n build_dir defaults to the current directory.\n temp_dir -- The location where temporary files (*.o or *.obj)\n from the build are placed. This location must be \n writable. If it isn't, several default locations are \n tried. It defaults to tempfile.gettempdir()\n verbose -- 0, 1, or 2. 0 is as quiet as possible. 1 prints\n minimal information. 2 is noisy. \n **kw -- keyword arguments. These are passed on to the \n distutils extension module. Most of the keywords\n are listed below.\n\n Distutils keywords. These are cut and pasted from Greg Ward's\n distutils.extension.Extension class for convenience:\n \n sources : [string]\n list of source filenames, relative to the distribution root\n (where the setup script lives), in Unix form (slash-separated)\n for portability. Source files may be C, C++, SWIG (.i),\n platform-specific resource files, or whatever else is recognized\n by the \"build_ext\" command as source for a Python extension.\n Note: The module_path file is always appended to the front of this\n list \n include_dirs : [string]\n list of directories to search for C/C++ header files (in Unix\n form for portability) \n define_macros : [(name : string, value : string|None)]\n list of macros to define; each macro is defined using a 2-tuple,\n where 'value' is either the string to define it to or None to\n define it without a particular value (equivalent of \"#define\n FOO\" in source or -DFOO on Unix C compiler command line) \n undef_macros : [string]\n list of macros to undefine explicitly\n library_dirs : [string]\n list of directories to search for C/C++ libraries at link time\n libraries : [string]\n list of library names (not filenames or paths) to link against\n runtime_library_dirs : [string]\n list of directories to search for C/C++ libraries at run time\n (for shared extensions, this is when the extension is loaded)\n extra_objects : [string]\n list of extra files to link with (eg. object files not implied\n by 'sources', static library that must be explicitly specified,\n binary resource files, etc.)\n extra_compile_args : [string]\n any extra platform- and compiler-specific information to use\n when compiling the source files in 'sources'. For platforms and\n compilers where \"command line\" makes sense, this is typically a\n list of command-line arguments, but for other platforms it could\n be anything.\n extra_link_args : [string]\n any extra platform- and compiler-specific information to use\n when linking object files together to create the extension (or\n to create a new static Python interpreter). Similar\n interpretation as for 'extra_compile_args'.\n export_symbols : [string]\n list of symbols to be exported from a shared extension. Not\n used on all platforms, and not generally necessary for Python\n extensions, which typically export exactly one symbol: \"init\" +\n extension_name.\n \"\"\"\n success = 0\n from distutils.core import setup, Extension\n \n # this is a screwy trick to get rid of a ton of warnings on Unix\n import distutils.sysconfig\n distutils.sysconfig.get_config_vars()\n if distutils.sysconfig._config_vars.has_key('OPT'):\n flags = distutils.sysconfig._config_vars['OPT'] \n flags = flags.replace('-Wall','')\n distutils.sysconfig._config_vars['OPT'] = flags\n \n # get the name of the module and the extension directory it lives in. \n module_dir,cpp_name = os.path.split(os.path.abspath(module_path))\n module_name,ext = os.path.splitext(cpp_name) \n \n # configure temp and build directories\n temp_dir = configure_temp_dir(temp_dir) \n build_dir = configure_build_dir(module_dir)\n \n compiler_name = choose_compiler(compiler_name)\n configure_sys_argv(compiler_name,temp_dir,build_dir)\n \n # the business end of the function\n try:\n if verbose == 1:\n print 'Compiling code...'\n \n # set compiler verboseness 2 or more makes it output results\n if verbose > 1: verb = 1 \n else: verb = 0\n \n t1 = time.time() \n # add module to the needed source code files and build extension\n sources = kw.get('sources',[])\n kw['sources'] = [module_path] + sources \n \n # add module to the needed source code files and build extension\n # FIX this is g++ specific. It probably should be fixed for other\n # Unices/compilers. Find a generic solution\n if compiler_name != 'msvc':\n libraries = kw.get('libraries',[])\n kw['libraries'] = ['stdc++'] + libraries \n \n # SunOS specific\n # fix for issue with linking to libstdc++.a. see:\n # http://mail.python.org/pipermail/python-dev/2001-March/013510.html\n platform = sys.platform\n version = sys.version.lower()\n if platform[:5] == 'sunos' and version.find('gcc') != -1:\n extra_link_args = kw.get('extra_link_args',[])\n kw['extra_link_args'] = ['-mimpure-text'] + extra_link_args\n \n ext = Extension(module_name, **kw)\n \n # the switcheroo on SystemExit here is meant to keep command line\n # sessions from exiting when compiles fail.\n builtin = sys.modules['__builtin__']\n old_SysExit = builtin.__dict__['SystemExit']\n builtin.__dict__['SystemExit'] = CompileError\n \n # distutils for MSVC messes with the environment, so we save the\n # current state and restore them afterward.\n import copy\n environ = copy.deepcopy(os.environ)\n try:\n setup(name = module_name, ext_modules = [ext],verbose=verb)\n finally:\n # restore state\n os.environ = environ \n # restore SystemExit\n builtin.__dict__['SystemExit'] = old_SysExit\n t2 = time.time()\n \n if verbose == 1:\n print 'finished compiling (sec): ', t2 - t1 \n success = 1\n configure_python_path(build_dir)\n except SyntaxError: #TypeError:\n success = 0 \n \n # restore argv after our trick... \n restore_sys_argv()\n \n return success\n\nold_argv = []\ndef configure_sys_argv(compiler_name,temp_dir,build_dir):\n # We're gonna play some tricks with argv here to pass info to distutils \n # which is really built for command line use. better way??\n global old_argv\n old_argv = sys.argv[:] \n sys.argv = ['','build_ext','--build-lib', build_dir,\n '--build-temp',temp_dir] \n if compiler_name == 'gcc':\n sys.argv.insert(2,'--compiler='+compiler_name)\n elif compiler_name:\n sys.argv.insert(2,'--compiler='+compiler_name)\n\ndef restore_sys_argv():\n sys.argv = old_argv\n \ndef configure_python_path(build_dir): \n #make sure the module lives in a directory on the python path.\n python_paths = [os.path.abspath(x) for x in sys.path]\n if os.path.abspath(build_dir) not in python_paths:\n #print \"warning: build directory was not part of python path.\"\\\n # \" It has been appended to the path.\"\n sys.path.append(os.path.abspath(build_dir))\n\ndef choose_compiler(compiler_name=''):\n \"\"\" Try and figure out which compiler is gonna be used on windows.\n On other platforms, it just returns whatever value it is given.\n \n converts 'gcc' to 'mingw32' on win32\n \"\"\"\n if sys.platform == 'win32': \n if not compiler_name:\n # On Windows, default to MSVC and use gcc if it wasn't found\n # wasn't found. If neither are found, go with whatever\n # the default is for distutils -- and probably fail...\n if msvc_exists():\n compiler_name = 'msvc'\n elif gcc_exists():\n compiler_name = 'mingw32'\n elif compiler_name == 'gcc':\n compiler_name = 'mingw32'\n else:\n # don't know how to force gcc -- look into this.\n if compiler_name == 'gcc':\n compiler_name = 'unix' \n return compiler_name\n \ndef gcc_exists():\n \"\"\" Test to make sure gcc is found \n \n Does this return correct value on win98???\n \"\"\"\n result = 0\n try:\n w,r=os.popen4('gcc -v')\n w.close()\n str_result = r.read()\n #print str_result\n if string.find(str_result,'Reading specs') != -1:\n result = 1\n except:\n # This was needed because the msvc compiler messes with\n # the path variable. and will occasionlly mess things up\n # so much that gcc is lost in the path. (Occurs in test\n # scripts)\n result = not os.system('gcc -v')\n return result\n\ndef msvc_exists():\n \"\"\" Determine whether MSVC is available on the machine.\n \"\"\"\n result = 0\n try:\n w,r=os.popen4('cl')\n w.close()\n str_result = r.read()\n #print str_result\n if string.find(str_result,'Microsoft') != -1:\n result = 1\n except:\n #assume we're ok if devstudio exists\n import distutils.msvccompiler\n version = distutils.msvccompiler.get_devstudio_version()\n if version:\n result = 1\n return result\n\ndef configure_temp_dir(temp_dir=None):\n if temp_dir is None: \n temp_dir = tempfile.gettempdir()\n elif not os.path.exists(temp_dir) or not os.access(temp_dir,os.W_OK):\n print \"warning: specified temp_dir '%s' does not exist or is \" \\\n \"or is not writable. Using the default temp directory\" % \\\n temp_dir\n temp_dir = tempfile.gettempdir()\n\n # final check that that directories are writable. \n if not os.access(temp_dir,os.W_OK):\n msg = \"Either the temp or build directory wasn't writable. Check\" \\\n \" these locations: '%s'\" % temp_dir \n raise ValueError, msg\n return temp_dir\n\ndef configure_build_dir(build_dir=None):\n # make sure build_dir exists and is writable\n if build_dir and (not os.path.exists(build_dir) or \n not os.access(build_dir,os.W_OK)):\n print \"warning: specified build_dir '%s' does not exist or is \" \\\n \"or is not writable. Trying default locations\" % build_dir\n build_dir = None\n \n if build_dir is None:\n #default to building in the home directory of the given module. \n build_dir = os.curdir\n # if it doesn't work use the current directory. This should always\n # be writable. \n if not os.access(build_dir,os.W_OK):\n print \"warning:, neither the module's directory nor the \"\\\n \"current directory are writable. Using the temporary\"\\\n \"directory.\"\n build_dir = tempfile.gettempdir()\n\n # final check that that directories are writable.\n if not os.access(build_dir,os.W_OK):\n msg = \"The build directory wasn't writable. Check\" \\\n \" this location: '%s'\" % build_dir\n raise ValueError, msg\n \n return os.path.abspath(build_dir) \n \nif sys.platform == 'win32':\n import distutils.cygwinccompiler\n # the same as cygwin plus some additional parameters\n class Mingw32CCompiler (distutils.cygwinccompiler.CygwinCCompiler):\n \"\"\" A modified MingW32 compiler compatible with an MSVC built Python.\n \n \"\"\"\n \n compiler_type = 'mingw32'\n \n def __init__ (self,\n verbose=0,\n dry_run=0,\n force=0):\n \n distutils.cygwinccompiler.CygwinCCompiler.__init__ (self, verbose, \n dry_run, force)\n \n # A real mingw32 doesn't need to specify a different entry point,\n # but cygwin 2.91.57 in no-cygwin-mode needs it.\n if self.gcc_version <= \"2.91.57\":\n entry_point = '--entry _DllMain@12'\n else:\n entry_point = ''\n if self.linker_dll == 'dllwrap':\n self.linker = 'dllwrap' + ' --driver-name g++'\n elif self.linker_dll == 'gcc':\n self.linker = 'g++' \n # **changes: eric jones 4/11/01\n # 1. Check for import library on Windows. Build if it doesn't exist.\n if not import_library_exists():\n build_import_library()\n \n # **changes: eric jones 4/11/01\n # 2. increased optimization and turned off all warnings\n # 3. also added --driver-name g++\n #self.set_executables(compiler='gcc -mno-cygwin -O2 -w',\n # compiler_so='gcc -mno-cygwin -mdll -O2 -w',\n # linker_exe='gcc -mno-cygwin',\n # linker_so='%s --driver-name g++ -mno-cygwin -mdll -static %s' \n # % (self.linker, entry_point))\n self.set_executables(compiler='g++ -mno-cygwin -O2 -w',\n compiler_so='g++ -mno-cygwin -mdll -O2 -w -Wstrict-prototypes',\n linker_exe='g++ -mno-cygwin',\n linker_so='%s -mno-cygwin -mdll -static %s' \n % (self.linker, entry_point))\n \n # Maybe we should also append -mthreads, but then the finished\n # dlls need another dll (mingwm10.dll see Mingw32 docs)\n # (-mthreads: Support thread-safe exception handling on `Mingw32') \n \n # no additional libraries needed \n self.dll_libraries=[]\n \n # __init__ ()\n \n # On windows platforms, we want to default to mingw32 (gcc)\n # because msvc can't build blitz stuff.\n # We should also check the version of gcc available...\n #distutils.ccompiler._default_compilers['nt'] = 'mingw32'\n #distutils.ccompiler._default_compilers = (('nt', 'mingw32'))\n # reset the Mingw32 compiler in distutils to the one defined above\n distutils.cygwinccompiler.Mingw32CCompiler = Mingw32CCompiler\n \n def import_library_exists():\n \"\"\" on windows platforms, make sure a gcc import library exists\n \"\"\"\n if os.name == 'nt':\n lib_name = \"libpython%d%d.a\" % tuple(sys.version_info[:2])\n full_path = os.path.join(sys.prefix,'libs',lib_name)\n if not os.path.exists(full_path):\n return 0\n return 1\n \n def build_import_library():\n \"\"\" Build the import libraries for Mingw32-gcc on Windows\n \"\"\"\n import lib2def as lib2def\n #libfile, deffile = parse_cmd()\n #if deffile == None:\n # deffile = sys.stdout\n #else:\n # deffile = open(deffile, 'w')\n lib_name = \"python%d%d.lib\" % tuple(sys.version_info[:2]) \n lib_file = os.path.join(sys.prefix,'libs',lib_name)\n def_name = \"python%d%d.def\" % tuple(sys.version_info[:2]) \n def_file = os.path.join(sys.prefix,'libs',def_name)\n nm_cmd = '%s %s' % (lib2def.DEFAULT_NM, lib_file)\n nm_output = lib2def.getnm(nm_cmd)\n dlist, flist = lib2def.parse_nm(nm_output)\n lib2def.output_def(dlist, flist, lib2def.DEF_HEADER, open(def_file, 'w'))\n \n out_name = \"libpython%d%d.a\" % tuple(sys.version_info[:2])\n out_file = os.path.join(sys.prefix,'libs',out_name)\n dll_name = \"python%d%d.dll\" % tuple(sys.version_info[:2])\n args = (dll_name,def_file,out_file)\n cmd = 'dlltool --dllname %s --def %s --output-lib %s' % args\n success = not os.system(cmd)\n # for now, fail silently\n if not success:\n print 'WARNING: failed to build import library for gcc. Linking will fail.'\n #if not success:\n # msg = \"Couldn't find import library, and failed to build it.\"\n # raise DistutilsPlatformError, msg\n \ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\n\n\n", "methods": [ { "name": "_init_posix", "long_name": "_init_posix( )", "filename": "build_tools.py", "nloc": 4, "complexity": 1, "token_count": 34, "parameters": [], "start_line": 30, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 0 }, { "name": "build_extension", "long_name": "build_extension( module_path , compiler_name = '' , build_dir = None , temp_dir = None , verbose = 0 , ** kw )", "filename": "build_tools.py", "nloc": 49, "complexity": 9, "token_count": 364, "parameters": [ "module_path", "compiler_name", "build_dir", "temp_dir", "verbose", "kw" ], "start_line": 42, "end_line": 212, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 171, "top_nesting_level": 0 }, { "name": "configure_sys_argv", "long_name": "configure_sys_argv( compiler_name , temp_dir , build_dir )", "filename": "build_tools.py", "nloc": 9, "complexity": 3, "token_count": 68, "parameters": [ "compiler_name", "temp_dir", "build_dir" ], "start_line": 215, "end_line": 225, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 }, { "name": "restore_sys_argv", "long_name": "restore_sys_argv( )", "filename": "build_tools.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [], "start_line": 227, "end_line": 228, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "configure_python_path", "long_name": "configure_python_path( build_dir )", "filename": "build_tools.py", "nloc": 4, "complexity": 3, "token_count": 51, "parameters": [ "build_dir" ], "start_line": 230, "end_line": 236, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "choose_compiler", "long_name": "choose_compiler( compiler_name = '' )", "filename": "build_tools.py", "nloc": 13, "complexity": 7, "token_count": 55, "parameters": [ "compiler_name" ], "start_line": 238, "end_line": 259, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 0 }, { "name": "gcc_exists", "long_name": "gcc_exists( )", "filename": "build_tools.py", "nloc": 11, "complexity": 3, "token_count": 61, "parameters": [], "start_line": 261, "end_line": 280, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 0 }, { "name": "msvc_exists", "long_name": "msvc_exists( )", "filename": "build_tools.py", "nloc": 14, "complexity": 4, "token_count": 71, "parameters": [], "start_line": 282, "end_line": 299, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 18, "top_nesting_level": 0 }, { "name": "configure_temp_dir", "long_name": "configure_temp_dir( temp_dir = None )", "filename": "build_tools.py", "nloc": 13, "complexity": 5, "token_count": 82, "parameters": [ "temp_dir" ], "start_line": 301, "end_line": 315, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "configure_build_dir", "long_name": "configure_build_dir( build_dir = None )", "filename": "build_tools.py", "nloc": 18, "complexity": 7, "token_count": 112, "parameters": [ "build_dir" ], "start_line": 317, "end_line": 342, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 26, "top_nesting_level": 0 }, { "name": "__init__", "long_name": "__init__( self , verbose = 0 , dry_run = 0 , force = 0 )", "filename": "build_tools.py", "nloc": 22, "complexity": 5, "token_count": 117, "parameters": [ "self", "verbose", "dry_run", "force" ], "start_line": 354, "end_line": 396, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 43, "top_nesting_level": 2 }, { "name": "import_library_exists", "long_name": "import_library_exists( )", "filename": "build_tools.py", "nloc": 7, "complexity": 3, "token_count": 57, "parameters": [], "start_line": 408, "end_line": 416, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "build_import_library", "long_name": "build_import_library( )", "filename": "build_tools.py", "nloc": 18, "complexity": 2, "token_count": 190, "parameters": [], "start_line": 418, "end_line": 444, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 27, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "build_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 449, "end_line": 451, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "build_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 453, "end_line": 455, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "build_extension", "long_name": "build_extension( module_path , compiler_name = '' , build_dir = None , temp_dir = None , verbose = 0 , ** kw )", "filename": "build_tools.py", "nloc": 52, "complexity": 10, "token_count": 390, "parameters": [ "module_path", "compiler_name", "build_dir", "temp_dir", "verbose", "kw" ], "start_line": 27, "end_line": 194, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 168, "top_nesting_level": 0 }, { "name": "configure_sys_argv", "long_name": "configure_sys_argv( compiler_name , temp_dir , build_dir )", "filename": "build_tools.py", "nloc": 9, "complexity": 3, "token_count": 68, "parameters": [ "compiler_name", "temp_dir", "build_dir" ], "start_line": 197, "end_line": 207, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 }, { "name": "restore_sys_argv", "long_name": "restore_sys_argv( )", "filename": "build_tools.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [], "start_line": 209, "end_line": 210, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "configure_python_path", "long_name": "configure_python_path( build_dir )", "filename": "build_tools.py", "nloc": 4, "complexity": 3, "token_count": 51, "parameters": [ "build_dir" ], "start_line": 212, "end_line": 218, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "choose_compiler", "long_name": "choose_compiler( compiler_name = '' )", "filename": "build_tools.py", "nloc": 13, "complexity": 7, "token_count": 55, "parameters": [ "compiler_name" ], "start_line": 220, "end_line": 241, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 0 }, { "name": "gcc_exists", "long_name": "gcc_exists( )", "filename": "build_tools.py", "nloc": 11, "complexity": 3, "token_count": 61, "parameters": [], "start_line": 243, "end_line": 262, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 0 }, { "name": "msvc_exists", "long_name": "msvc_exists( )", "filename": "build_tools.py", "nloc": 14, "complexity": 4, "token_count": 71, "parameters": [], "start_line": 264, "end_line": 281, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 18, "top_nesting_level": 0 }, { "name": "configure_temp_dir", "long_name": "configure_temp_dir( temp_dir = None )", "filename": "build_tools.py", "nloc": 13, "complexity": 5, "token_count": 82, "parameters": [ "temp_dir" ], "start_line": 283, "end_line": 297, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "configure_build_dir", "long_name": "configure_build_dir( build_dir = None )", "filename": "build_tools.py", "nloc": 18, "complexity": 7, "token_count": 112, "parameters": [ "build_dir" ], "start_line": 299, "end_line": 324, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 26, "top_nesting_level": 0 }, { "name": "__init__", "long_name": "__init__( self , verbose = 0 , dry_run = 0 , force = 0 )", "filename": "build_tools.py", "nloc": 22, "complexity": 5, "token_count": 117, "parameters": [ "self", "verbose", "dry_run", "force" ], "start_line": 336, "end_line": 378, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 43, "top_nesting_level": 2 }, { "name": "import_library_exists", "long_name": "import_library_exists( )", "filename": "build_tools.py", "nloc": 7, "complexity": 3, "token_count": 57, "parameters": [], "start_line": 390, "end_line": 398, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "build_import_library", "long_name": "build_import_library( )", "filename": "build_tools.py", "nloc": 18, "complexity": 2, "token_count": 190, "parameters": [], "start_line": 400, "end_line": 426, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 27, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "build_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 431, "end_line": 433, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "build_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 435, "end_line": 437, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "_init_posix", "long_name": "_init_posix( )", "filename": "build_tools.py", "nloc": 4, "complexity": 1, "token_count": 34, "parameters": [], "start_line": 30, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 0 }, { "name": "build_extension", "long_name": "build_extension( module_path , compiler_name = '' , build_dir = None , temp_dir = None , verbose = 0 , ** kw )", "filename": "build_tools.py", "nloc": 49, "complexity": 9, "token_count": 364, "parameters": [ "module_path", "compiler_name", "build_dir", "temp_dir", "verbose", "kw" ], "start_line": 42, "end_line": 212, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 171, "top_nesting_level": 0 } ], "nloc": 225, "complexity": 55, "token_count": 1391, "diff_parsed": { "added": [ "# If linker is 'gcc', this will convert it to 'g++'", "# necessary to make sure stdc++ is linked in cross-platform way.", "import distutils.sysconfig", "", "old_init_posix = distutils.sysconfig._init_posix", "", "def _init_posix():", " old_init_posix()", " ld = distutils.sysconfig._config_vars['LDSHARED']", " distutils.sysconfig._config_vars['LDSHARED'] = ld.replace('gcc','g++')", "", "distutils.sysconfig._init_posix = _init_posix", "# end force g++", "", "", " # ! This was fixed at beginning of file by using g++ on most", " # !machines. We'll have to check how to handle it on non-gcc machines", " ## add module to the needed source code files and build extension", " ## FIX this is g++ specific. It probably should be fixed for other", " ## Unices/compilers. Find a generic solution", " #if compiler_name != 'msvc':", " # libraries = kw.get('libraries',[])", " # kw['libraries'] = ['stdc++'] + libraries", " # !" ], "deleted": [ " # add module to the needed source code files and build extension", " # FIX this is g++ specific. It probably should be fixed for other", " # Unices/compilers. Find a generic solution", " if compiler_name != 'msvc':", " libraries = kw.get('libraries',[])", " kw['libraries'] = ['stdc++'] + libraries" ] } } ] }, { "hash": "79cd95adf1c70d464b266d1fd84e1d98781117b1", "msg": "Minor changes for better f2py support", "author": { "name": "Pearu Peterson", "email": "pearu.peterson@gmail.com" }, "committer": { "name": "Pearu Peterson", "email": "pearu.peterson@gmail.com" }, "author_date": "2002-01-16T19:10:10+00:00", "author_timezone": 0, "committer_date": "2002-01-16T19:10:10+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "c9d6cb8e55c5bd9fc27b359e3f87530b1e602288" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 3, "insertions": 10, "lines": 13, "files": 3, "dmm_unit_size": 0.0, "dmm_unit_complexity": 0.0, "dmm_unit_interfacing": 0.0, "modified_files": [ { "old_path": "scipy_distutils/__version__.py", "new_path": "scipy_distutils/__version__.py", "filename": "__version__.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -1,4 +1,4 @@\n # This file is automatically updated with update_version\n # function from scipy_distutils.misc_util.py\n-version = '0.6.23-alpha-90'\n-version_info = (0, 6, 23, 'alpha', 90)\n+version = '0.6.23-alpha-93'\n+version_info = (0, 6, 23, 'alpha', 93)\n", "added_lines": 2, "deleted_lines": 2, "source_code": "# This file is automatically updated with update_version\n# function from scipy_distutils.misc_util.py\nversion = '0.6.23-alpha-93'\nversion_info = (0, 6, 23, 'alpha', 93)\n", "source_code_before": "# This file is automatically updated with update_version\n# function from scipy_distutils.misc_util.py\nversion = '0.6.23-alpha-90'\nversion_info = (0, 6, 23, 'alpha', 90)\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 2, "complexity": 0, "token_count": 16, "diff_parsed": { "added": [ "version = '0.6.23-alpha-93'", "version_info = (0, 6, 23, 'alpha', 93)" ], "deleted": [ "version = '0.6.23-alpha-90'", "version_info = (0, 6, 23, 'alpha', 90)" ] } }, { "old_path": "scipy_distutils/command/build_flib.py", "new_path": "scipy_distutils/command/build_flib.py", "filename": "build_flib.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -49,6 +49,11 @@\n from distutils.command.build_clib import build_clib\n from distutils.errors import *\n \n+class FortranCompilerError (CCompilerError):\n+ \"\"\"Some compile/link operation failed.\"\"\"\n+class FortranCompileError (FortranCompilerError):\n+ \"\"\"Failure to compile one or more Fortran source files.\"\"\"\n+\n if os.name == 'nt':\n def run_command(command):\n \"\"\" not sure how to get exit status on nt. \"\"\"\n@@ -286,7 +291,7 @@ def f_compile(self,compiler,switches, source_files,\n print cmd\n failure = os.system(cmd)\n if failure:\n- raise ValueError, 'failure during compile' \n+ raise FortranCompileError, 'failure during compile' \n object_files.append(object)\n return object_files\n #return all object files to make sure everything is archived \n", "added_lines": 6, "deleted_lines": 1, "source_code": "\"\"\" Implements the build_flib command which should go into Distutils\n at some point.\n \n Note:\n Right now, we're dynamically linking to the Fortran libraries on \n some platforms (Sun for sure). This is fine for local installations\n but a bad thing for redistribution because these libraries won't\n live on any machine that doesn't have a fortran compiler installed.\n It is pretty hard (impossible?) to get gcc to pass the right compiler\n flags on Sun to get the linker to use static libs for the fortran\n stuff. Investigate further...\n\nBugs:\n *** Options -e and -x have no effect when used with --help-compiler\n options. E.g. \n ./setup.py build_flib --help-compiler -e g77-3.0\n finds g77-2.95.\n How to extract these options inside the show_compilers function?\n *** compiler.is_available() method may not work correctly on nt\n because of lack of knowledge how to get exit status in\n run_command function. However, it may give reasonable results\n based on a version string.\n *** Some vendors provide different compilers for F77 and F90\n compilations. Currently, checking the availability of these\n compilers is based on only checking the availability of the\n corresponding F77 compiler. If it exists, then F90 is assumed\n to exist also.\n\nOpen issues:\n *** User-defined compiler flags. Do we need --fflags?\n\nFortran compilers (as to be used with --fcompiler= option):\n Absoft\n Sun\n SGI\n Intel\n Itanium\n NAG\n Compaq\n Gnu\n VAST\n\"\"\"\n\nimport distutils\nimport distutils.dep_util, distutils.dir_util\nimport os,sys,string\nimport commands,re\nfrom types import *\nfrom distutils.command.build_clib import build_clib\nfrom distutils.errors import *\n\nclass FortranCompilerError (CCompilerError):\n \"\"\"Some compile/link operation failed.\"\"\"\nclass FortranCompileError (FortranCompilerError):\n \"\"\"Failure to compile one or more Fortran source files.\"\"\"\n\nif os.name == 'nt':\n def run_command(command):\n \"\"\" not sure how to get exit status on nt. \"\"\"\n in_pipe,out_pipe = os.popen4(command)\n in_pipe.close()\n text = out_pipe.read()\n return 0, text\nelse:\n run_command = commands.getstatusoutput\n \ndef show_compilers():\n for compiler_class in all_compilers:\n compiler = compiler_class()\n if compiler.is_available():\n print compiler\n\nclass build_flib (build_clib):\n\n description = \"build f77/f90 libraries used by Python extensions\"\n\n user_options = [\n ('build-flib', 'b',\n \"directory to build f77/f90 libraries to\"),\n ('build-temp', 't',\n \"directory to put temporary build by-products\"),\n ('debug', 'g',\n \"compile with debugging information\"),\n ('force', 'f',\n \"forcibly build everything (ignore file timestamps)\"),\n ('fcompiler=', 'c',\n \"specify the compiler type\"),\n ('fcompiler-exec=', 'e',\n \"specify the path to F77 compiler\"),\n ('f90compiler-exec=', 'x',\n \"specify the path to F90 compiler\"),\n ]\n\n boolean_options = ['debug', 'force']\n\n help_options = [\n ('help-compiler', None,\n \"list available compilers\", show_compilers),\n ]\n\n def initialize_options (self):\n\n self.build_flib = None\n self.build_temp = None\n\n self.fortran_libraries = None\n self.define = None\n self.undef = None\n self.debug = None\n self.force = 0\n self.fcompiler = None\n self.fcompiler_exec = None\n self.f90compiler_exec = None\n\n # initialize_options()\n\n def finalize_options (self):\n self.set_undefined_options('build',\n ('build_temp', 'build_flib'),\n ('build_temp', 'build_temp'),\n ('debug', 'debug'),\n ('force', 'force'))\n fc = find_fortran_compiler(self.fcompiler,\n self.fcompiler_exec,\n self.f90compiler_exec)\n if not fc:\n raise DistutilsOptionError, 'Fortran compiler not available: %s'%(self.fcompiler)\n else:\n self.announce(' using %s Fortran compiler' % fc)\n self.fcompiler = fc\n if self.has_f_libraries():\n self.fortran_libraries = self.distribution.fortran_libraries\n self.check_library_list(self.fortran_libraries)\n\n # finalize_options()\n\n def has_f_libraries(self):\n return self.distribution.fortran_libraries \\\n and len(self.distribution.fortran_libraries) > 0\n\n def run (self):\n if not self.has_f_libraries():\n return\n self.build_libraries(self.fortran_libraries)\n\n # run ()\n\n def get_library_names(self):\n if not self.has_f_libraries():\n return None\n\n lib_names = [] \n\n for (lib_name, build_info) in self.fortran_libraries:\n lib_names.append(lib_name)\n\n if self.fcompiler is not None:\n lib_names.extend(self.fcompiler.get_libraries())\n \n return lib_names\n\n # get_library_names ()\n\n def get_library_dirs(self):\n if not self.has_f_libraries():\n return []#None\n\n lib_dirs = [] \n\n if self.fcompiler is not None:\n lib_dirs.extend(self.fcompiler.get_library_dirs())\n \n return lib_dirs\n\n # get_library_dirs ()\n\n def get_runtime_library_dirs(self):\n if not self.has_f_libraries():\n return []#None\n\n lib_dirs = [] \n\n if self.fcompiler is not None:\n lib_dirs.extend(self.fcompiler.get_runtime_library_dirs())\n \n return lib_dirs\n\n # get_library_dirs ()\n\n def get_source_files (self):\n self.check_library_list(self.fortran_libraries)\n filenames = []\n\n # Gets source files specified \n for ext in self.fortran_libraries:\n filenames.extend(ext[1]['sources'])\n\n return filenames \n \n def build_libraries (self, fortran_libraries):\n \n fcompiler = self.fcompiler\n \n for (lib_name, build_info) in fortran_libraries:\n sources = build_info.get('sources')\n if sources is None or type(sources) not in (ListType, TupleType):\n raise DistutilsSetupError, \\\n (\"in 'fortran_libraries' option (library '%s'), \" +\n \"'sources' must be present and must be \" +\n \"a list of source filenames\") % lib_name\n sources = list(sources)\n module_dirs = build_info.get('module_dirs')\n module_files = build_info.get('module_files')\n self.announce(\" building '%s' library\" % lib_name)\n \n if module_files:\n fcompiler.build_library(lib_name, module_files,\n temp_dir=self.build_temp)\n \n fcompiler.build_library(lib_name, sources,\n module_dirs, temp_dir=self.build_temp)\n\n # for loop\n\n # build_libraries ()\n\n\nclass fortran_compiler_base:\n\n vendor = None\n ver_match = None\n \n def __init__(self):\n # Default initialization. Constructors of derived classes MUST\n # call this functions.\n self.version = None\n \n self.f77_switches = ''\n self.f77_opt = ''\n self.f77_debug = ''\n \n self.f90_switches = ''\n self.f90_opt = ''\n self.f90_debug = ''\n \n self.libraries = []\n self.library_dirs = []\n\n if self.vendor is None:\n raise DistutilsInternalError,\\\n '%s must define vendor attribute'%(self.__class__)\n if self.ver_match is None:\n raise DistutilsInternalError,\\\n '%s must define ver_match attribute'%(self.__class__)\n\n def to_object(self,dirty_files,module_dirs=None, temp_dir=''):\n files = string.join(dirty_files)\n f90_files = get_f90_files(dirty_files)\n f77_files = get_f77_files(dirty_files)\n if f90_files != []:\n obj1 = self.f90_compile(f90_files,module_dirs,temp_dir = temp_dir)\n else:\n obj1 = []\n if f77_files != []:\n obj2 = self.f77_compile(f77_files, temp_dir = temp_dir)\n else:\n obj2 = []\n return obj1 + obj2\n\n def source_to_object_names(self,source_files, temp_dir=''):\n file_list = map(lambda x: os.path.basename(x),source_files)\n file_base_ext = map(lambda x: os.path.splitext(x),file_list)\n object_list = map(lambda x: x[0] +'.o',file_base_ext)\n object_files = map(lambda x,td=temp_dir: os.path.join(td,x),object_list)\n return object_files\n \n def source_and_object_pairs(self,source_files, temp_dir=''):\n object_files = self.source_to_object_names(source_files,temp_dir)\n file_pairs = zip(source_files,object_files)\n return file_pairs\n \n def f_compile(self,compiler,switches, source_files,\n module_dirs=None, temp_dir=''):\n module_switch = self.build_module_switch(module_dirs)\n file_pairs = self.source_and_object_pairs(source_files,temp_dir)\n object_files = []\n for source,object in file_pairs:\n if distutils.dep_util.newer(source,object):\n cmd = compiler + ' ' + switches + \\\n module_switch + ' -c ' + source + ' -o ' + object \n print cmd\n failure = os.system(cmd)\n if failure:\n raise FortranCompileError, 'failure during compile' \n object_files.append(object)\n return object_files\n #return all object files to make sure everything is archived \n #return map(lambda x: x[1], file_pairs)\n\n def f90_compile(self,source_files,module_dirs=None, temp_dir=''):\n switches = string.join((self.f90_switches, self.f90_opt))\n return self.f_compile(self.f90_compiler,switches,\n source_files, module_dirs,temp_dir)\n\n def f77_compile(self,source_files,module_dirs=None, temp_dir=''):\n switches = string.join((self.f77_switches, self.f77_opt))\n return self.f_compile(self.f77_compiler,switches,\n source_files, module_dirs,temp_dir)\n\n\n def build_module_switch(self, module_dirs):\n return ''\n\n def create_static_lib(self, object_files, library_name,\n output_dir='', debug=None):\n lib_file = os.path.join(output_dir,'lib'+library_name+'.a')\n newer = distutils.dep_util.newer\n # This doesn't work -- no way to know if the file is in the archive\n #object_files = filter(lambda o,lib=lib_file:\\\n # distutils.dep_util.newer(o,lib),object_files)\n objects = string.join(object_files)\n if objects:\n cmd = 'ar -cur %s %s' % (lib_file,objects)\n print cmd\n os.system(cmd)\n\n def build_library(self,library_name,source_list,module_dirs=None,\n temp_dir = ''):\n #make sure the temp directory exists before trying to build files\n import distutils.dir_util\n distutils.dir_util.mkpath(temp_dir)\n #this compiles the files\n object_list = self.to_object(source_list,module_dirs,temp_dir)\n # actually we need to use all the object file names here to\n # make sure the library is always built. It could occur that an\n # object file exists but hasn't been put in the archive. (happens\n # a lot when builds fail once and are restarted).\n object_list = self.source_to_object_names(source_list, temp_dir)\n #self.create_static_lib(object_list,library_name,temp_dir) \n # This is pure bunk...\n # Windows fails for long argument strings on the command line.\n # if objects is real long (> 2048 chars or so on my machine),\n # the command fails (cmd.exe /e:2048 on w2k)\n # for now we'll split linking into to steps which should work for\n objects = object_list[:]\n while objects:\n obj,objects = objects[:20],objects[20:]\n self.create_static_lib(obj,library_name,temp_dir)\n\n def dummy_fortran_files(self):\n import tempfile \n d = tempfile.gettempdir()\n dummy_name = os.path.join(d,'__dummy.f')\n dummy = open(dummy_name,'w')\n dummy.write(\" subroutine dummy()\\n end\\n\")\n dummy.close()\n return (os.path.join(d,'__dummy.f'),os.path.join(d,'__dummy.o'))\n \n def is_available(self):\n return self.get_version()\n \n def get_version(self):\n \"\"\"Return the compiler version. If compiler is not available,\n return empty string.\"\"\"\n # XXX: Is there compilers that have no version? If yes,\n # this test will fail even if the compiler is available.\n if self.version is not None:\n # Finding version is expensive, so return previously found\n # version string.\n return self.version\n self.version = ''\n # works I think only for unix... \n #print 'command:', self.ver_cmd\n exit_status, out_text = run_command(self.ver_cmd)\n #print exit_status, out_text\n if not exit_status:\n m = re.match(self.ver_match,out_text)\n if m:\n self.version = m.group('version')\n return self.version\n\n def get_libraries(self):\n return self.libraries\n def get_library_dirs(self):\n return self.library_dirs\n def get_extra_link_args(self):\n return []\n def get_runtime_library_dirs(self):\n return []\n def get_linker_so(self):\n \"\"\"\n If a compiler requires specific linker then return a list\n containing a linker executable name and linker options.\n Otherwise, return None.\n \"\"\"\n\n def __str__(self):\n return \"%s %s\" % (self.vendor, self.get_version())\n\n\nclass absoft_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Absoft'\n ver_match = r'FORTRAN 77 Compiler (?P[^\\s*,]*).*?Absoft Corp'\n \n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if fc is None:\n fc = 'f77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n # got rid of -B108 cause it was generating 2 underscores instead\n # of one on the newest version. Now we use -YEXT_SFX=_ to \n # specify the output format\n if os.name == 'nt':\n self.f90_switches = '-f fixed -YCFRL=1 -YCOM_NAMES=LCS' \\\n ' -YCOM_PFX -YEXT_PFX -YEXT_NAMES=LCS' \\\n ' -YCOM_SFX=_ -YEXT_SFX=_ -YEXT_NAMES=LCS' \n self.f90_opt = '-O -Q100'\n self.f77_switches = '-N22 -N90 -N110'\n self.f77_opt = '-O -Q100'\n self.libraries = ['fio', 'fmath', 'f90math', 'COMDLG32']\n else:\n self.f90_switches = '-ffixed -YCFRL=1 -YCOM_NAMES=LCS' \\\n ' -YCOM_PFX -YEXT_PFX -YEXT_NAMES=LCS' \\\n ' -YCOM_SFX=_ -YEXT_SFX=_ -YEXT_NAMES=LCS' \n self.f90_opt = '-O -B101' \n self.f77_switches = '-N22 -N90 -N110 -B108'\n self.f77_opt = '-O -B101'\n\n self.libraries = ['fio', 'f77math', 'f90math']\n \n try:\n dir = os.environ['ABSOFT'] \n self.library_dirs = [os.path.join(dir,'lib')]\n except KeyError:\n self.library_dirs = []\n\n self.ver_cmd = self.f77_compiler + ' -V -c %s -o %s' % \\\n self.dummy_fortran_files()\n\n def build_module_switch(self,module_dirs):\n res = ''\n if module_dirs:\n for mod in module_dirs:\n res = res + ' -p' + mod\n return res\n\n def get_extra_link_args(self):\n return []\n # Couldn't get this to link for anything using gcc.\n #dr = \"c:\\\\Absoft62\\\\lib\"\n #libs = ['fio.lib', 'COMDLG32.lib','fmath.lib', 'f90math.lib','libcomdlg32.a' ] \n #libs = map(lambda x,dr=dr:os.path.join(dr,x),libs)\n #return libs\n\n\nclass sun_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Sun'\n ver_match = r'f77: (?P[^\\s*,]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if fc is None:\n fc = 'f77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc # not tested\n self.f77_switches = ' -pic '\n self.f77_opt = ' -fast -dalign '\n\n self.f90_compiler = f90c\n self.f90_switches = ' -fixed ' # ??? why fixed?\n self.f90_opt = ' -fast -dalign '\n\n self.libraries = ['f90', 'F77', 'M77', 'sunmath', 'm']\n #threaded\n #self.libraries = ['f90', 'F77_mt', 'sunmath_mt', 'm', 'thread']\n #self.libraries = []\n self.library_dirs = self.find_lib_dir()\n #print 'sun:',self.library_dirs\n\n self.ver_cmd = self.f77_compiler + ' -V'\n\n def build_module_switch(self,module_dirs):\n res = ''\n if module_dirs:\n for mod in module_dirs:\n res = res + ' -M' + mod\n return res\n\n def find_lib_dir(self):\n library_dirs = []\n lib_match = r'### f90: Note: LD_RUN_PATH\\s*= '\\\n '(?P[^\\s.]*).*'\n cmd = self.f90_compiler + ' -dryrun dummy.f'\n exit_status, output = run_command(cmd)\n if not exit_status:\n libs = re.findall(lib_match,output)\n if libs:\n library_dirs = string.split(libs[0],':')\n self.get_version() # force version calculation\n compiler_home = os.path.dirname(library_dirs[0])\n library_dirs.append(os.path.join(compiler_home,\n self.version,'lib'))\n return library_dirs\n def get_runtime_library_dirs(self):\n return self.find_lib_dir()\n def get_extra_link_args(self):\n return ['-mimpure-text']\n\n\nclass mips_fortran_compiler(fortran_compiler_base):\n\n vendor = 'SGI'\n ver_match = r'MIPSpro Compilers: Version (?P[^\\s*,]*)'\n \n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if fc is None:\n fc = 'f77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc # not tested\n self.f77_switches = ' -n32 -KPIC '\n self.f77_opt = ' -O3 '\n\n self.f90_compiler = f90c\n self.f90_switches = ' -n32 -KPIC -fixedform ' # why fixed ???\n self.f90_opt = ' ' \n \n self.libraries = ['fortran', 'ftn', 'm']\n self.library_dirs = self.find_lib_dir()\n\n self.ver_cmd = self.f77_compiler + ' -version'\n\n def build_module_switch(self,module_dirs):\n res = ''\n return res \n def find_lib_dir(self):\n library_dirs = []\n return library_dirs\n def get_runtime_library_dirs(self):\n\treturn self.find_lib_dir() \n def get_extra_link_args(self):\n\treturn []\n\n\nclass gnu_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Gnu'\n ver_match = r'g77 version (?P[^\\s*]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if sys.platform == 'win32':\n self.libraries = ['gcc','g2c']\n self.library_dirs = self.find_lib_directories()\n\n if fc is None:\n fc = 'g77'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n\n switches = ' -Wall -fno-second-underscore '\n\n if os.name != 'nt':\n switches = switches + ' -fpic '\n\n self.f77_switches = switches\n\n self.ver_cmd = self.f77_compiler + ' -v '\n self.f77_opt = self.get_opt()\n\n def get_opt(self):\n import cpuinfo\n cpu = cpuinfo.cpuinfo()\n opt = ' -O3 -funroll-loops '\n \n # only check for more optimization if g77 can handle\n # it.\n if self.get_version():\n if self.version[0]=='3': # is g77 3.x.x\n if cpu.is_AthlonK6():\n opt = opt + ' -march=k6 '\n elif cpu.is_AthlonK7():\n opt = opt + ' -march=athlon '\n if cpu.is_i686():\n opt = opt + ' -march=i686 '\n elif cpu.is_i586():\n opt = opt + ' -march=i586 '\n elif cpu.is_i486():\n opt = opt + ' -march=i486 '\n elif cpu.is_i386():\n opt = opt + ' -march=i386 '\n if cpu.is_Intel():\n opt = opt + ' -malign-double ' \n return opt\n \n def find_lib_directories(self):\n lib_dir = []\n match = r'Reading specs from (.*)/specs'\n\n # works I think only for unix... \n exit_status, out_text = run_command('g77 -v')\n if not exit_status:\n m = re.findall(match,out_text)\n if m:\n lib_dir= m #m[0] \n return lib_dir\n\n def get_linker_so(self):\n # win32 linking should be handled by standard linker\n if sys.platform != 'win32':\n return [self.f77_compiler,'-shared']\n \n def f90_compile(self,source_files,module_files,temp_dir=''):\n raise DistutilsExecError, 'f90 not supported by Gnu'\n\n\n#http://developer.intel.com/software/products/compilers/f50/linux/\nclass intel_ia32_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Intel' # Intel(R) Corporation \n ver_match = r'Intel\\(R\\) Fortran Compiler for 32-bit applications, Version (?P[^\\s*]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'ifc'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n switches = ' -KPIC '\n\n import cpuinfo\n cpu = cpuinfo.cpuinfo()\n if cpu.has_fdiv_bug():\n switches = switches + ' -fdiv_check '\n if cpu.has_f00f_bug():\n switches = switches + ' -0f_check '\n self.f77_switches = self.f90_switches = switches\n self.f77_switches = self.f77_switches + ' -FI -w90 -w95 '\n\n self.f77_opt = self.f90_opt = self.get_opt()\n \n debug = ' -g -C '\n self.f77_debug = self.f90_debug = debug\n\n self.ver_cmd = self.f77_compiler+' -FI -V -c %s -o %s' %\\\n self.dummy_fortran_files()\n\n def get_opt(self):\n import cpuinfo\n cpu = cpuinfo.cpuinfo()\n opt = ' -O3 '\n if cpu.is_PentiumPro() or cpu.is_PentiumII():\n opt = opt + ' -tpp6 -xi '\n elif cpu.is_PentiumIII():\n opt = opt + ' -tpp6 '\n elif cpu.is_Pentium():\n opt = opt + ' -tpp5 '\n elif cpu.is_PentiumIV():\n opt = opt + ' -tpp7 -xW '\n elif cpu.has_mmx():\n opt = opt + ' -xM '\n return opt\n \n\n def get_linker_so(self):\n return [self.f77_compiler,'-shared']\n\n\nclass intel_itanium_fortran_compiler(intel_ia32_fortran_compiler):\n\n vendor = 'Itanium'\n ver_match = r'Intel\\(R\\) Fortran 90 Compiler Itanium\\(TM\\) Compiler for the Itanium\\(TM\\)-based applications, Version (?P[^\\s*]*)'\n\n def __init__(self, fc = None, f90c = None):\n if fc is None:\n fc = 'efc'\n intel_ia32_fortran_compiler.__init__(self, fc, f90c)\n\n\nclass nag_fortran_compiler(fortran_compiler_base):\n\n vendor = 'NAG'\n ver_match = r'NAGWare Fortran 95 compiler Release (?P[^\\s]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'f95'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n switches = ''\n debug = ' -g -gline -g90 -nan -C '\n\n self.f77_switches = self.f90_switches = switches\n self.f77_switches = self.f77_switches + ' -fixed '\n self.f77_debug = self.f90_debug = debug\n self.f77_opt = self.f90_opt = self.get_opt()\n\n self.ver_cmd = self.f77_compiler+' -V '\n\n def get_opt(self):\n opt = ' -O4 -target=native '\n return opt\n\n def get_linker_so(self):\n return [self.f77_compiler,'-Wl,-shared']\n\n\nclass vast_fortran_compiler(fortran_compiler_base):\n\n vendor = 'VAST'\n ver_match = r'\\s*Pacific-Sierra Research vf90 (Personal|Professional)\\s+(?P[^\\s]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'g77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n d,b = os.path.split(f90c)\n vf90 = os.path.join(d,'v'+b)\n self.ver_cmd = vf90+' -v '\n\n gnu = gnu_fortran_compiler(fc)\n if not gnu.is_available(): # VAST compiler requires g77.\n self.version = ''\n return\n if not self.is_available():\n return\n\n self.f77_switches = gnu.f77_switches\n self.f77_debug = gnu.f77_debug\n self.f77_opt = gnu.f77_opt \n\n # XXX: need f90 switches, debug, opt\n\n def get_linker_so(self):\n return [self.f90_compiler,'-shared']\n\nclass compaq_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Compaq'\n ver_match = r'Compaq Fortran (?P[^\\s]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'fort'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n switches = ' -assume no2underscore -nomixed_str_len_arg '\n debug = ' -g -check_bounds '\n\n self.f77_switches = self.f90_switches = switches\n self.f77_debug = self.f90_debug = debug\n self.f77_opt = self.f90_opt = self.get_opt()\n\n # XXX: uncomment if required\n #self.libraries = ' -lUfor -lfor -lFutil -lcpml -lots -lc '\n\n # XXX: fix the version showing flag\n self.ver_cmd = self.f77_compiler+' -V '\n\n def get_opt(self):\n opt = ' -O4 -align dcommons -arch host -assume bigarrays -assume nozsize -math_library fast -tune host '\n return opt\n\n def get_linker_so(self):\n # XXX: is -shared needed?\n return [self.f77_compiler,'-shared']\n\n\ndef match_extension(files,ext):\n match = re.compile(r'.*[.]('+ext+r')\\Z',re.I).match\n return filter(lambda x,match = match: match(x),files)\n\ndef get_f77_files(files):\n return match_extension(files,'for|f77|ftn|f')\n\ndef get_f90_files(files):\n return match_extension(files,'f90|f95')\n\ndef get_fortran_files(files):\n return match_extension(files,'f90|f95|for|f77|ftn|f')\n\ndef find_fortran_compiler(vendor = None, fc = None, f90c = None):\n fcompiler = None\n for compiler_class in all_compilers:\n if vendor is not None and vendor != compiler_class.vendor:\n continue\n print compiler_class\n compiler = compiler_class(fc,f90c)\n if compiler.is_available():\n fcompiler = compiler\n break\n return fcompiler\n\nall_compilers = [absoft_fortran_compiler,\n mips_fortran_compiler,\n sun_fortran_compiler,\n intel_ia32_fortran_compiler,\n intel_itanium_fortran_compiler,\n nag_fortran_compiler,\n compaq_fortran_compiler,\n vast_fortran_compiler,\n gnu_fortran_compiler,\n ]\n\nif __name__ == \"__main__\":\n show_compilers()\n", "source_code_before": "\"\"\" Implements the build_flib command which should go into Distutils\n at some point.\n \n Note:\n Right now, we're dynamically linking to the Fortran libraries on \n some platforms (Sun for sure). This is fine for local installations\n but a bad thing for redistribution because these libraries won't\n live on any machine that doesn't have a fortran compiler installed.\n It is pretty hard (impossible?) to get gcc to pass the right compiler\n flags on Sun to get the linker to use static libs for the fortran\n stuff. Investigate further...\n\nBugs:\n *** Options -e and -x have no effect when used with --help-compiler\n options. E.g. \n ./setup.py build_flib --help-compiler -e g77-3.0\n finds g77-2.95.\n How to extract these options inside the show_compilers function?\n *** compiler.is_available() method may not work correctly on nt\n because of lack of knowledge how to get exit status in\n run_command function. However, it may give reasonable results\n based on a version string.\n *** Some vendors provide different compilers for F77 and F90\n compilations. Currently, checking the availability of these\n compilers is based on only checking the availability of the\n corresponding F77 compiler. If it exists, then F90 is assumed\n to exist also.\n\nOpen issues:\n *** User-defined compiler flags. Do we need --fflags?\n\nFortran compilers (as to be used with --fcompiler= option):\n Absoft\n Sun\n SGI\n Intel\n Itanium\n NAG\n Compaq\n Gnu\n VAST\n\"\"\"\n\nimport distutils\nimport distutils.dep_util, distutils.dir_util\nimport os,sys,string\nimport commands,re\nfrom types import *\nfrom distutils.command.build_clib import build_clib\nfrom distutils.errors import *\n\nif os.name == 'nt':\n def run_command(command):\n \"\"\" not sure how to get exit status on nt. \"\"\"\n in_pipe,out_pipe = os.popen4(command)\n in_pipe.close()\n text = out_pipe.read()\n return 0, text\nelse:\n run_command = commands.getstatusoutput\n \ndef show_compilers():\n for compiler_class in all_compilers:\n compiler = compiler_class()\n if compiler.is_available():\n print compiler\n\nclass build_flib (build_clib):\n\n description = \"build f77/f90 libraries used by Python extensions\"\n\n user_options = [\n ('build-flib', 'b',\n \"directory to build f77/f90 libraries to\"),\n ('build-temp', 't',\n \"directory to put temporary build by-products\"),\n ('debug', 'g',\n \"compile with debugging information\"),\n ('force', 'f',\n \"forcibly build everything (ignore file timestamps)\"),\n ('fcompiler=', 'c',\n \"specify the compiler type\"),\n ('fcompiler-exec=', 'e',\n \"specify the path to F77 compiler\"),\n ('f90compiler-exec=', 'x',\n \"specify the path to F90 compiler\"),\n ]\n\n boolean_options = ['debug', 'force']\n\n help_options = [\n ('help-compiler', None,\n \"list available compilers\", show_compilers),\n ]\n\n def initialize_options (self):\n\n self.build_flib = None\n self.build_temp = None\n\n self.fortran_libraries = None\n self.define = None\n self.undef = None\n self.debug = None\n self.force = 0\n self.fcompiler = None\n self.fcompiler_exec = None\n self.f90compiler_exec = None\n\n # initialize_options()\n\n def finalize_options (self):\n self.set_undefined_options('build',\n ('build_temp', 'build_flib'),\n ('build_temp', 'build_temp'),\n ('debug', 'debug'),\n ('force', 'force'))\n fc = find_fortran_compiler(self.fcompiler,\n self.fcompiler_exec,\n self.f90compiler_exec)\n if not fc:\n raise DistutilsOptionError, 'Fortran compiler not available: %s'%(self.fcompiler)\n else:\n self.announce(' using %s Fortran compiler' % fc)\n self.fcompiler = fc\n if self.has_f_libraries():\n self.fortran_libraries = self.distribution.fortran_libraries\n self.check_library_list(self.fortran_libraries)\n\n # finalize_options()\n\n def has_f_libraries(self):\n return self.distribution.fortran_libraries \\\n and len(self.distribution.fortran_libraries) > 0\n\n def run (self):\n if not self.has_f_libraries():\n return\n self.build_libraries(self.fortran_libraries)\n\n # run ()\n\n def get_library_names(self):\n if not self.has_f_libraries():\n return None\n\n lib_names = [] \n\n for (lib_name, build_info) in self.fortran_libraries:\n lib_names.append(lib_name)\n\n if self.fcompiler is not None:\n lib_names.extend(self.fcompiler.get_libraries())\n \n return lib_names\n\n # get_library_names ()\n\n def get_library_dirs(self):\n if not self.has_f_libraries():\n return []#None\n\n lib_dirs = [] \n\n if self.fcompiler is not None:\n lib_dirs.extend(self.fcompiler.get_library_dirs())\n \n return lib_dirs\n\n # get_library_dirs ()\n\n def get_runtime_library_dirs(self):\n if not self.has_f_libraries():\n return []#None\n\n lib_dirs = [] \n\n if self.fcompiler is not None:\n lib_dirs.extend(self.fcompiler.get_runtime_library_dirs())\n \n return lib_dirs\n\n # get_library_dirs ()\n\n def get_source_files (self):\n self.check_library_list(self.fortran_libraries)\n filenames = []\n\n # Gets source files specified \n for ext in self.fortran_libraries:\n filenames.extend(ext[1]['sources'])\n\n return filenames \n \n def build_libraries (self, fortran_libraries):\n \n fcompiler = self.fcompiler\n \n for (lib_name, build_info) in fortran_libraries:\n sources = build_info.get('sources')\n if sources is None or type(sources) not in (ListType, TupleType):\n raise DistutilsSetupError, \\\n (\"in 'fortran_libraries' option (library '%s'), \" +\n \"'sources' must be present and must be \" +\n \"a list of source filenames\") % lib_name\n sources = list(sources)\n module_dirs = build_info.get('module_dirs')\n module_files = build_info.get('module_files')\n self.announce(\" building '%s' library\" % lib_name)\n \n if module_files:\n fcompiler.build_library(lib_name, module_files,\n temp_dir=self.build_temp)\n \n fcompiler.build_library(lib_name, sources,\n module_dirs, temp_dir=self.build_temp)\n\n # for loop\n\n # build_libraries ()\n\n\nclass fortran_compiler_base:\n\n vendor = None\n ver_match = None\n \n def __init__(self):\n # Default initialization. Constructors of derived classes MUST\n # call this functions.\n self.version = None\n \n self.f77_switches = ''\n self.f77_opt = ''\n self.f77_debug = ''\n \n self.f90_switches = ''\n self.f90_opt = ''\n self.f90_debug = ''\n \n self.libraries = []\n self.library_dirs = []\n\n if self.vendor is None:\n raise DistutilsInternalError,\\\n '%s must define vendor attribute'%(self.__class__)\n if self.ver_match is None:\n raise DistutilsInternalError,\\\n '%s must define ver_match attribute'%(self.__class__)\n\n def to_object(self,dirty_files,module_dirs=None, temp_dir=''):\n files = string.join(dirty_files)\n f90_files = get_f90_files(dirty_files)\n f77_files = get_f77_files(dirty_files)\n if f90_files != []:\n obj1 = self.f90_compile(f90_files,module_dirs,temp_dir = temp_dir)\n else:\n obj1 = []\n if f77_files != []:\n obj2 = self.f77_compile(f77_files, temp_dir = temp_dir)\n else:\n obj2 = []\n return obj1 + obj2\n\n def source_to_object_names(self,source_files, temp_dir=''):\n file_list = map(lambda x: os.path.basename(x),source_files)\n file_base_ext = map(lambda x: os.path.splitext(x),file_list)\n object_list = map(lambda x: x[0] +'.o',file_base_ext)\n object_files = map(lambda x,td=temp_dir: os.path.join(td,x),object_list)\n return object_files\n \n def source_and_object_pairs(self,source_files, temp_dir=''):\n object_files = self.source_to_object_names(source_files,temp_dir)\n file_pairs = zip(source_files,object_files)\n return file_pairs\n \n def f_compile(self,compiler,switches, source_files,\n module_dirs=None, temp_dir=''):\n module_switch = self.build_module_switch(module_dirs)\n file_pairs = self.source_and_object_pairs(source_files,temp_dir)\n object_files = []\n for source,object in file_pairs:\n if distutils.dep_util.newer(source,object):\n cmd = compiler + ' ' + switches + \\\n module_switch + ' -c ' + source + ' -o ' + object \n print cmd\n failure = os.system(cmd)\n if failure:\n raise ValueError, 'failure during compile' \n object_files.append(object)\n return object_files\n #return all object files to make sure everything is archived \n #return map(lambda x: x[1], file_pairs)\n\n def f90_compile(self,source_files,module_dirs=None, temp_dir=''):\n switches = string.join((self.f90_switches, self.f90_opt))\n return self.f_compile(self.f90_compiler,switches,\n source_files, module_dirs,temp_dir)\n\n def f77_compile(self,source_files,module_dirs=None, temp_dir=''):\n switches = string.join((self.f77_switches, self.f77_opt))\n return self.f_compile(self.f77_compiler,switches,\n source_files, module_dirs,temp_dir)\n\n\n def build_module_switch(self, module_dirs):\n return ''\n\n def create_static_lib(self, object_files, library_name,\n output_dir='', debug=None):\n lib_file = os.path.join(output_dir,'lib'+library_name+'.a')\n newer = distutils.dep_util.newer\n # This doesn't work -- no way to know if the file is in the archive\n #object_files = filter(lambda o,lib=lib_file:\\\n # distutils.dep_util.newer(o,lib),object_files)\n objects = string.join(object_files)\n if objects:\n cmd = 'ar -cur %s %s' % (lib_file,objects)\n print cmd\n os.system(cmd)\n\n def build_library(self,library_name,source_list,module_dirs=None,\n temp_dir = ''):\n #make sure the temp directory exists before trying to build files\n import distutils.dir_util\n distutils.dir_util.mkpath(temp_dir)\n #this compiles the files\n object_list = self.to_object(source_list,module_dirs,temp_dir)\n # actually we need to use all the object file names here to\n # make sure the library is always built. It could occur that an\n # object file exists but hasn't been put in the archive. (happens\n # a lot when builds fail once and are restarted).\n object_list = self.source_to_object_names(source_list, temp_dir)\n #self.create_static_lib(object_list,library_name,temp_dir) \n # This is pure bunk...\n # Windows fails for long argument strings on the command line.\n # if objects is real long (> 2048 chars or so on my machine),\n # the command fails (cmd.exe /e:2048 on w2k)\n # for now we'll split linking into to steps which should work for\n objects = object_list[:]\n while objects:\n obj,objects = objects[:20],objects[20:]\n self.create_static_lib(obj,library_name,temp_dir)\n\n def dummy_fortran_files(self):\n import tempfile \n d = tempfile.gettempdir()\n dummy_name = os.path.join(d,'__dummy.f')\n dummy = open(dummy_name,'w')\n dummy.write(\" subroutine dummy()\\n end\\n\")\n dummy.close()\n return (os.path.join(d,'__dummy.f'),os.path.join(d,'__dummy.o'))\n \n def is_available(self):\n return self.get_version()\n \n def get_version(self):\n \"\"\"Return the compiler version. If compiler is not available,\n return empty string.\"\"\"\n # XXX: Is there compilers that have no version? If yes,\n # this test will fail even if the compiler is available.\n if self.version is not None:\n # Finding version is expensive, so return previously found\n # version string.\n return self.version\n self.version = ''\n # works I think only for unix... \n #print 'command:', self.ver_cmd\n exit_status, out_text = run_command(self.ver_cmd)\n #print exit_status, out_text\n if not exit_status:\n m = re.match(self.ver_match,out_text)\n if m:\n self.version = m.group('version')\n return self.version\n\n def get_libraries(self):\n return self.libraries\n def get_library_dirs(self):\n return self.library_dirs\n def get_extra_link_args(self):\n return []\n def get_runtime_library_dirs(self):\n return []\n def get_linker_so(self):\n \"\"\"\n If a compiler requires specific linker then return a list\n containing a linker executable name and linker options.\n Otherwise, return None.\n \"\"\"\n\n def __str__(self):\n return \"%s %s\" % (self.vendor, self.get_version())\n\n\nclass absoft_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Absoft'\n ver_match = r'FORTRAN 77 Compiler (?P[^\\s*,]*).*?Absoft Corp'\n \n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if fc is None:\n fc = 'f77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n # got rid of -B108 cause it was generating 2 underscores instead\n # of one on the newest version. Now we use -YEXT_SFX=_ to \n # specify the output format\n if os.name == 'nt':\n self.f90_switches = '-f fixed -YCFRL=1 -YCOM_NAMES=LCS' \\\n ' -YCOM_PFX -YEXT_PFX -YEXT_NAMES=LCS' \\\n ' -YCOM_SFX=_ -YEXT_SFX=_ -YEXT_NAMES=LCS' \n self.f90_opt = '-O -Q100'\n self.f77_switches = '-N22 -N90 -N110'\n self.f77_opt = '-O -Q100'\n self.libraries = ['fio', 'fmath', 'f90math', 'COMDLG32']\n else:\n self.f90_switches = '-ffixed -YCFRL=1 -YCOM_NAMES=LCS' \\\n ' -YCOM_PFX -YEXT_PFX -YEXT_NAMES=LCS' \\\n ' -YCOM_SFX=_ -YEXT_SFX=_ -YEXT_NAMES=LCS' \n self.f90_opt = '-O -B101' \n self.f77_switches = '-N22 -N90 -N110 -B108'\n self.f77_opt = '-O -B101'\n\n self.libraries = ['fio', 'f77math', 'f90math']\n \n try:\n dir = os.environ['ABSOFT'] \n self.library_dirs = [os.path.join(dir,'lib')]\n except KeyError:\n self.library_dirs = []\n\n self.ver_cmd = self.f77_compiler + ' -V -c %s -o %s' % \\\n self.dummy_fortran_files()\n\n def build_module_switch(self,module_dirs):\n res = ''\n if module_dirs:\n for mod in module_dirs:\n res = res + ' -p' + mod\n return res\n\n def get_extra_link_args(self):\n return []\n # Couldn't get this to link for anything using gcc.\n #dr = \"c:\\\\Absoft62\\\\lib\"\n #libs = ['fio.lib', 'COMDLG32.lib','fmath.lib', 'f90math.lib','libcomdlg32.a' ] \n #libs = map(lambda x,dr=dr:os.path.join(dr,x),libs)\n #return libs\n\n\nclass sun_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Sun'\n ver_match = r'f77: (?P[^\\s*,]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if fc is None:\n fc = 'f77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc # not tested\n self.f77_switches = ' -pic '\n self.f77_opt = ' -fast -dalign '\n\n self.f90_compiler = f90c\n self.f90_switches = ' -fixed ' # ??? why fixed?\n self.f90_opt = ' -fast -dalign '\n\n self.libraries = ['f90', 'F77', 'M77', 'sunmath', 'm']\n #threaded\n #self.libraries = ['f90', 'F77_mt', 'sunmath_mt', 'm', 'thread']\n #self.libraries = []\n self.library_dirs = self.find_lib_dir()\n #print 'sun:',self.library_dirs\n\n self.ver_cmd = self.f77_compiler + ' -V'\n\n def build_module_switch(self,module_dirs):\n res = ''\n if module_dirs:\n for mod in module_dirs:\n res = res + ' -M' + mod\n return res\n\n def find_lib_dir(self):\n library_dirs = []\n lib_match = r'### f90: Note: LD_RUN_PATH\\s*= '\\\n '(?P[^\\s.]*).*'\n cmd = self.f90_compiler + ' -dryrun dummy.f'\n exit_status, output = run_command(cmd)\n if not exit_status:\n libs = re.findall(lib_match,output)\n if libs:\n library_dirs = string.split(libs[0],':')\n self.get_version() # force version calculation\n compiler_home = os.path.dirname(library_dirs[0])\n library_dirs.append(os.path.join(compiler_home,\n self.version,'lib'))\n return library_dirs\n def get_runtime_library_dirs(self):\n return self.find_lib_dir()\n def get_extra_link_args(self):\n return ['-mimpure-text']\n\n\nclass mips_fortran_compiler(fortran_compiler_base):\n\n vendor = 'SGI'\n ver_match = r'MIPSpro Compilers: Version (?P[^\\s*,]*)'\n \n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if fc is None:\n fc = 'f77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc # not tested\n self.f77_switches = ' -n32 -KPIC '\n self.f77_opt = ' -O3 '\n\n self.f90_compiler = f90c\n self.f90_switches = ' -n32 -KPIC -fixedform ' # why fixed ???\n self.f90_opt = ' ' \n \n self.libraries = ['fortran', 'ftn', 'm']\n self.library_dirs = self.find_lib_dir()\n\n self.ver_cmd = self.f77_compiler + ' -version'\n\n def build_module_switch(self,module_dirs):\n res = ''\n return res \n def find_lib_dir(self):\n library_dirs = []\n return library_dirs\n def get_runtime_library_dirs(self):\n\treturn self.find_lib_dir() \n def get_extra_link_args(self):\n\treturn []\n\n\nclass gnu_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Gnu'\n ver_match = r'g77 version (?P[^\\s*]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n if sys.platform == 'win32':\n self.libraries = ['gcc','g2c']\n self.library_dirs = self.find_lib_directories()\n\n if fc is None:\n fc = 'g77'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n\n switches = ' -Wall -fno-second-underscore '\n\n if os.name != 'nt':\n switches = switches + ' -fpic '\n\n self.f77_switches = switches\n\n self.ver_cmd = self.f77_compiler + ' -v '\n self.f77_opt = self.get_opt()\n\n def get_opt(self):\n import cpuinfo\n cpu = cpuinfo.cpuinfo()\n opt = ' -O3 -funroll-loops '\n \n # only check for more optimization if g77 can handle\n # it.\n if self.get_version():\n if self.version[0]=='3': # is g77 3.x.x\n if cpu.is_AthlonK6():\n opt = opt + ' -march=k6 '\n elif cpu.is_AthlonK7():\n opt = opt + ' -march=athlon '\n if cpu.is_i686():\n opt = opt + ' -march=i686 '\n elif cpu.is_i586():\n opt = opt + ' -march=i586 '\n elif cpu.is_i486():\n opt = opt + ' -march=i486 '\n elif cpu.is_i386():\n opt = opt + ' -march=i386 '\n if cpu.is_Intel():\n opt = opt + ' -malign-double ' \n return opt\n \n def find_lib_directories(self):\n lib_dir = []\n match = r'Reading specs from (.*)/specs'\n\n # works I think only for unix... \n exit_status, out_text = run_command('g77 -v')\n if not exit_status:\n m = re.findall(match,out_text)\n if m:\n lib_dir= m #m[0] \n return lib_dir\n\n def get_linker_so(self):\n # win32 linking should be handled by standard linker\n if sys.platform != 'win32':\n return [self.f77_compiler,'-shared']\n \n def f90_compile(self,source_files,module_files,temp_dir=''):\n raise DistutilsExecError, 'f90 not supported by Gnu'\n\n\n#http://developer.intel.com/software/products/compilers/f50/linux/\nclass intel_ia32_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Intel' # Intel(R) Corporation \n ver_match = r'Intel\\(R\\) Fortran Compiler for 32-bit applications, Version (?P[^\\s*]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'ifc'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n switches = ' -KPIC '\n\n import cpuinfo\n cpu = cpuinfo.cpuinfo()\n if cpu.has_fdiv_bug():\n switches = switches + ' -fdiv_check '\n if cpu.has_f00f_bug():\n switches = switches + ' -0f_check '\n self.f77_switches = self.f90_switches = switches\n self.f77_switches = self.f77_switches + ' -FI -w90 -w95 '\n\n self.f77_opt = self.f90_opt = self.get_opt()\n \n debug = ' -g -C '\n self.f77_debug = self.f90_debug = debug\n\n self.ver_cmd = self.f77_compiler+' -FI -V -c %s -o %s' %\\\n self.dummy_fortran_files()\n\n def get_opt(self):\n import cpuinfo\n cpu = cpuinfo.cpuinfo()\n opt = ' -O3 '\n if cpu.is_PentiumPro() or cpu.is_PentiumII():\n opt = opt + ' -tpp6 -xi '\n elif cpu.is_PentiumIII():\n opt = opt + ' -tpp6 '\n elif cpu.is_Pentium():\n opt = opt + ' -tpp5 '\n elif cpu.is_PentiumIV():\n opt = opt + ' -tpp7 -xW '\n elif cpu.has_mmx():\n opt = opt + ' -xM '\n return opt\n \n\n def get_linker_so(self):\n return [self.f77_compiler,'-shared']\n\n\nclass intel_itanium_fortran_compiler(intel_ia32_fortran_compiler):\n\n vendor = 'Itanium'\n ver_match = r'Intel\\(R\\) Fortran 90 Compiler Itanium\\(TM\\) Compiler for the Itanium\\(TM\\)-based applications, Version (?P[^\\s*]*)'\n\n def __init__(self, fc = None, f90c = None):\n if fc is None:\n fc = 'efc'\n intel_ia32_fortran_compiler.__init__(self, fc, f90c)\n\n\nclass nag_fortran_compiler(fortran_compiler_base):\n\n vendor = 'NAG'\n ver_match = r'NAGWare Fortran 95 compiler Release (?P[^\\s]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'f95'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n switches = ''\n debug = ' -g -gline -g90 -nan -C '\n\n self.f77_switches = self.f90_switches = switches\n self.f77_switches = self.f77_switches + ' -fixed '\n self.f77_debug = self.f90_debug = debug\n self.f77_opt = self.f90_opt = self.get_opt()\n\n self.ver_cmd = self.f77_compiler+' -V '\n\n def get_opt(self):\n opt = ' -O4 -target=native '\n return opt\n\n def get_linker_so(self):\n return [self.f77_compiler,'-Wl,-shared']\n\n\nclass vast_fortran_compiler(fortran_compiler_base):\n\n vendor = 'VAST'\n ver_match = r'\\s*Pacific-Sierra Research vf90 (Personal|Professional)\\s+(?P[^\\s]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'g77'\n if f90c is None:\n f90c = 'f90'\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n d,b = os.path.split(f90c)\n vf90 = os.path.join(d,'v'+b)\n self.ver_cmd = vf90+' -v '\n\n gnu = gnu_fortran_compiler(fc)\n if not gnu.is_available(): # VAST compiler requires g77.\n self.version = ''\n return\n if not self.is_available():\n return\n\n self.f77_switches = gnu.f77_switches\n self.f77_debug = gnu.f77_debug\n self.f77_opt = gnu.f77_opt \n\n # XXX: need f90 switches, debug, opt\n\n def get_linker_so(self):\n return [self.f90_compiler,'-shared']\n\nclass compaq_fortran_compiler(fortran_compiler_base):\n\n vendor = 'Compaq'\n ver_match = r'Compaq Fortran (?P[^\\s]*)'\n\n def __init__(self, fc = None, f90c = None):\n fortran_compiler_base.__init__(self)\n\n if fc is None:\n fc = 'fort'\n if f90c is None:\n f90c = fc\n\n self.f77_compiler = fc\n self.f90_compiler = f90c\n\n switches = ' -assume no2underscore -nomixed_str_len_arg '\n debug = ' -g -check_bounds '\n\n self.f77_switches = self.f90_switches = switches\n self.f77_debug = self.f90_debug = debug\n self.f77_opt = self.f90_opt = self.get_opt()\n\n # XXX: uncomment if required\n #self.libraries = ' -lUfor -lfor -lFutil -lcpml -lots -lc '\n\n # XXX: fix the version showing flag\n self.ver_cmd = self.f77_compiler+' -V '\n\n def get_opt(self):\n opt = ' -O4 -align dcommons -arch host -assume bigarrays -assume nozsize -math_library fast -tune host '\n return opt\n\n def get_linker_so(self):\n # XXX: is -shared needed?\n return [self.f77_compiler,'-shared']\n\n\ndef match_extension(files,ext):\n match = re.compile(r'.*[.]('+ext+r')\\Z',re.I).match\n return filter(lambda x,match = match: match(x),files)\n\ndef get_f77_files(files):\n return match_extension(files,'for|f77|ftn|f')\n\ndef get_f90_files(files):\n return match_extension(files,'f90|f95')\n\ndef get_fortran_files(files):\n return match_extension(files,'f90|f95|for|f77|ftn|f')\n\ndef find_fortran_compiler(vendor = None, fc = None, f90c = None):\n fcompiler = None\n for compiler_class in all_compilers:\n if vendor is not None and vendor != compiler_class.vendor:\n continue\n print compiler_class\n compiler = compiler_class(fc,f90c)\n if compiler.is_available():\n fcompiler = compiler\n break\n return fcompiler\n\nall_compilers = [absoft_fortran_compiler,\n mips_fortran_compiler,\n sun_fortran_compiler,\n intel_ia32_fortran_compiler,\n intel_itanium_fortran_compiler,\n nag_fortran_compiler,\n compaq_fortran_compiler,\n vast_fortran_compiler,\n gnu_fortran_compiler,\n ]\n\nif __name__ == \"__main__\":\n show_compilers()\n", "methods": [ { "name": "run_command", "long_name": "run_command( command )", "filename": "build_flib.py", "nloc": 5, "complexity": 1, "token_count": 32, "parameters": [ "command" ], "start_line": 58, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "show_compilers", "long_name": "show_compilers( )", "filename": "build_flib.py", "nloc": 5, "complexity": 3, "token_count": 23, "parameters": [], "start_line": 67, "end_line": 71, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 }, { "name": "initialize_options", "long_name": "initialize_options( self )", "filename": "build_flib.py", "nloc": 11, "complexity": 1, "token_count": 55, "parameters": [ "self" ], "start_line": 101, "end_line": 113, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "finalize_options", "long_name": "finalize_options( self )", "filename": "build_flib.py", "nloc": 17, "complexity": 3, "token_count": 104, "parameters": [ "self" ], "start_line": 117, "end_line": 133, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 17, "top_nesting_level": 1 }, { "name": "has_f_libraries", "long_name": "has_f_libraries( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 2, "token_count": 23, "parameters": [ "self" ], "start_line": 137, "end_line": 139, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "run", "long_name": "run( self )", "filename": "build_flib.py", "nloc": 4, "complexity": 2, "token_count": 22, "parameters": [ "self" ], "start_line": 141, "end_line": 144, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "get_library_names", "long_name": "get_library_names( self )", "filename": "build_flib.py", "nloc": 9, "complexity": 4, "token_count": 58, "parameters": [ "self" ], "start_line": 148, "end_line": 160, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "get_library_dirs", "long_name": "get_library_dirs( self )", "filename": "build_flib.py", "nloc": 7, "complexity": 3, "token_count": 42, "parameters": [ "self" ], "start_line": 164, "end_line": 173, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 7, "complexity": 3, "token_count": 42, "parameters": [ "self" ], "start_line": 177, "end_line": 186, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "get_source_files", "long_name": "get_source_files( self )", "filename": "build_flib.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 190, "end_line": 198, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "build_libraries", "long_name": "build_libraries( self , fortran_libraries )", "filename": "build_flib.py", "nloc": 18, "complexity": 5, "token_count": 122, "parameters": [ "self", "fortran_libraries" ], "start_line": 200, "end_line": 221, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self )", "filename": "build_flib.py", "nloc": 16, "complexity": 3, "token_count": 88, "parameters": [ "self" ], "start_line": 233, "end_line": 254, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "to_object", "long_name": "to_object( self , dirty_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 13, "complexity": 3, "token_count": 89, "parameters": [ "self", "dirty_files", "module_dirs", "temp_dir" ], "start_line": 256, "end_line": 268, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "source_to_object_names", "long_name": "source_to_object_names( self , source_files , temp_dir = '' )", "filename": "build_flib.py", "nloc": 6, "complexity": 1, "token_count": 89, "parameters": [ "self", "source_files", "temp_dir" ], "start_line": 270, "end_line": 275, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "source_and_object_pairs", "long_name": "source_and_object_pairs( self , source_files , temp_dir = '' )", "filename": "build_flib.py", "nloc": 4, "complexity": 1, "token_count": 31, "parameters": [ "self", "source_files", "temp_dir" ], "start_line": 277, "end_line": 280, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "f_compile", "long_name": "f_compile( self , compiler , switches , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 15, "complexity": 4, "token_count": 103, "parameters": [ "self", "compiler", "switches", "source_files", "module_dirs", "temp_dir" ], "start_line": 282, "end_line": 296, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "f90_compile", "long_name": "f90_compile( self , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 4, "complexity": 1, "token_count": 48, "parameters": [ "self", "source_files", "module_dirs", "temp_dir" ], "start_line": 300, "end_line": 303, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "f77_compile", "long_name": "f77_compile( self , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 4, "complexity": 1, "token_count": 48, "parameters": [ "self", "source_files", "module_dirs", "temp_dir" ], "start_line": 305, "end_line": 308, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self", "module_dirs" ], "start_line": 311, "end_line": 312, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "create_static_lib", "long_name": "create_static_lib( self , object_files , library_name , output_dir = '' , debug = None )", "filename": "build_flib.py", "nloc": 9, "complexity": 2, "token_count": 68, "parameters": [ "self", "object_files", "library_name", "output_dir", "debug" ], "start_line": 314, "end_line": 325, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 1 }, { "name": "build_library", "long_name": "build_library( self , library_name , source_list , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 10, "complexity": 2, "token_count": 85, "parameters": [ "self", "library_name", "source_list", "module_dirs", "temp_dir" ], "start_line": 327, "end_line": 348, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "dummy_fortran_files", "long_name": "dummy_fortran_files( self )", "filename": "build_flib.py", "nloc": 8, "complexity": 1, "token_count": 69, "parameters": [ "self" ], "start_line": 350, "end_line": 357, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "is_available", "long_name": "is_available( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 359, "end_line": 360, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_version", "long_name": "get_version( self )", "filename": "build_flib.py", "nloc": 10, "complexity": 4, "token_count": 66, "parameters": [ "self" ], "start_line": 362, "end_line": 380, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 19, "top_nesting_level": 1 }, { "name": "get_libraries", "long_name": "get_libraries( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self" ], "start_line": 382, "end_line": 383, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_library_dirs", "long_name": "get_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self" ], "start_line": 384, "end_line": 385, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 386, "end_line": 387, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 388, "end_line": 389, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 1, "complexity": 1, "token_count": 6, "parameters": [ "self" ], "start_line": 390, "end_line": 395, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "__str__", "long_name": "__str__( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 397, "end_line": 398, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 31, "complexity": 5, "token_count": 177, "parameters": [ "self", "fc", "f90c" ], "start_line": 406, "end_line": 444, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 6, "complexity": 3, "token_count": 27, "parameters": [ "self", "module_dirs" ], "start_line": 446, "end_line": 451, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 453, "end_line": 454, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 98, "parameters": [ "self", "fc", "f90c" ], "start_line": 467, "end_line": 489, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 6, "complexity": 3, "token_count": 27, "parameters": [ "self", "module_dirs" ], "start_line": 491, "end_line": 496, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "find_lib_dir", "long_name": "find_lib_dir( self )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 99, "parameters": [ "self" ], "start_line": 498, "end_line": 512, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 513, "end_line": 514, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self" ], "start_line": 515, "end_line": 516, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 94, "parameters": [ "self", "fc", "f90c" ], "start_line": 524, "end_line": 542, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 19, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 12, "parameters": [ "self", "module_dirs" ], "start_line": 544, "end_line": 546, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "find_lib_dir", "long_name": "find_lib_dir( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 547, "end_line": 549, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 550, "end_line": 551, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 552, "end_line": 553, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 16, "complexity": 5, "token_count": 103, "parameters": [ "self", "fc", "f90c" ], "start_line": 561, "end_line": 582, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 21, "complexity": 10, "token_count": 120, "parameters": [ "self" ], "start_line": 584, "end_line": 607, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 24, "top_nesting_level": 1 }, { "name": "find_lib_directories", "long_name": "find_lib_directories( self )", "filename": "build_flib.py", "nloc": 9, "complexity": 3, "token_count": 43, "parameters": [ "self" ], "start_line": 609, "end_line": 619, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 2, "token_count": 20, "parameters": [ "self" ], "start_line": 621, "end_line": 624, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "f90_compile", "long_name": "f90_compile( self , source_files , module_files , temp_dir = '' )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 17, "parameters": [ "self", "source_files", "module_files", "temp_dir" ], "start_line": 626, "end_line": 627, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 22, "complexity": 5, "token_count": 140, "parameters": [ "self", "fc", "f90c" ], "start_line": 636, "end_line": 664, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 29, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 15, "complexity": 7, "token_count": 85, "parameters": [ "self" ], "start_line": 666, "end_line": 680, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 683, "end_line": 684, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 4, "complexity": 2, "token_count": 31, "parameters": [ "self", "fc", "f90c" ], "start_line": 692, "end_line": 695, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 100, "parameters": [ "self", "fc", "f90c" ], "start_line": 703, "end_line": 722, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 10, "parameters": [ "self" ], "start_line": 724, "end_line": 726, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 728, "end_line": 729, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 20, "complexity": 5, "token_count": 128, "parameters": [ "self", "fc", "f90c" ], "start_line": 737, "end_line": 761, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 765, "end_line": 766, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 14, "complexity": 3, "token_count": 91, "parameters": [ "self", "fc", "f90c" ], "start_line": 773, "end_line": 795, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 10, "parameters": [ "self" ], "start_line": 797, "end_line": 799, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 801, "end_line": 803, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "match_extension", "long_name": "match_extension( files , ext )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 44, "parameters": [ "files", "ext" ], "start_line": 806, "end_line": 808, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "get_f77_files", "long_name": "get_f77_files( files )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "files" ], "start_line": 810, "end_line": 811, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "get_f90_files", "long_name": "get_f90_files( files )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "files" ], "start_line": 813, "end_line": 814, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "get_fortran_files", "long_name": "get_fortran_files( files )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "files" ], "start_line": 816, "end_line": 817, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "find_fortran_compiler", "long_name": "find_fortran_compiler( vendor = None , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 11, "complexity": 5, "token_count": 59, "parameters": [ "vendor", "fc", "f90c" ], "start_line": 819, "end_line": 829, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 } ], "methods_before": [ { "name": "run_command", "long_name": "run_command( command )", "filename": "build_flib.py", "nloc": 5, "complexity": 1, "token_count": 32, "parameters": [ "command" ], "start_line": 53, "end_line": 58, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "show_compilers", "long_name": "show_compilers( )", "filename": "build_flib.py", "nloc": 5, "complexity": 3, "token_count": 23, "parameters": [], "start_line": 62, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 }, { "name": "initialize_options", "long_name": "initialize_options( self )", "filename": "build_flib.py", "nloc": 11, "complexity": 1, "token_count": 55, "parameters": [ "self" ], "start_line": 96, "end_line": 108, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "finalize_options", "long_name": "finalize_options( self )", "filename": "build_flib.py", "nloc": 17, "complexity": 3, "token_count": 104, "parameters": [ "self" ], "start_line": 112, "end_line": 128, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 17, "top_nesting_level": 1 }, { "name": "has_f_libraries", "long_name": "has_f_libraries( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 2, "token_count": 23, "parameters": [ "self" ], "start_line": 132, "end_line": 134, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "run", "long_name": "run( self )", "filename": "build_flib.py", "nloc": 4, "complexity": 2, "token_count": 22, "parameters": [ "self" ], "start_line": 136, "end_line": 139, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "get_library_names", "long_name": "get_library_names( self )", "filename": "build_flib.py", "nloc": 9, "complexity": 4, "token_count": 58, "parameters": [ "self" ], "start_line": 143, "end_line": 155, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "get_library_dirs", "long_name": "get_library_dirs( self )", "filename": "build_flib.py", "nloc": 7, "complexity": 3, "token_count": 42, "parameters": [ "self" ], "start_line": 159, "end_line": 168, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 7, "complexity": 3, "token_count": 42, "parameters": [ "self" ], "start_line": 172, "end_line": 181, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "get_source_files", "long_name": "get_source_files( self )", "filename": "build_flib.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 185, "end_line": 193, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "build_libraries", "long_name": "build_libraries( self , fortran_libraries )", "filename": "build_flib.py", "nloc": 18, "complexity": 5, "token_count": 122, "parameters": [ "self", "fortran_libraries" ], "start_line": 195, "end_line": 216, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self )", "filename": "build_flib.py", "nloc": 16, "complexity": 3, "token_count": 88, "parameters": [ "self" ], "start_line": 228, "end_line": 249, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "to_object", "long_name": "to_object( self , dirty_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 13, "complexity": 3, "token_count": 89, "parameters": [ "self", "dirty_files", "module_dirs", "temp_dir" ], "start_line": 251, "end_line": 263, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "source_to_object_names", "long_name": "source_to_object_names( self , source_files , temp_dir = '' )", "filename": "build_flib.py", "nloc": 6, "complexity": 1, "token_count": 89, "parameters": [ "self", "source_files", "temp_dir" ], "start_line": 265, "end_line": 270, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "source_and_object_pairs", "long_name": "source_and_object_pairs( self , source_files , temp_dir = '' )", "filename": "build_flib.py", "nloc": 4, "complexity": 1, "token_count": 31, "parameters": [ "self", "source_files", "temp_dir" ], "start_line": 272, "end_line": 275, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "f_compile", "long_name": "f_compile( self , compiler , switches , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 15, "complexity": 4, "token_count": 103, "parameters": [ "self", "compiler", "switches", "source_files", "module_dirs", "temp_dir" ], "start_line": 277, "end_line": 291, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "f90_compile", "long_name": "f90_compile( self , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 4, "complexity": 1, "token_count": 48, "parameters": [ "self", "source_files", "module_dirs", "temp_dir" ], "start_line": 295, "end_line": 298, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "f77_compile", "long_name": "f77_compile( self , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 4, "complexity": 1, "token_count": 48, "parameters": [ "self", "source_files", "module_dirs", "temp_dir" ], "start_line": 300, "end_line": 303, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self", "module_dirs" ], "start_line": 306, "end_line": 307, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "create_static_lib", "long_name": "create_static_lib( self , object_files , library_name , output_dir = '' , debug = None )", "filename": "build_flib.py", "nloc": 9, "complexity": 2, "token_count": 68, "parameters": [ "self", "object_files", "library_name", "output_dir", "debug" ], "start_line": 309, "end_line": 320, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 1 }, { "name": "build_library", "long_name": "build_library( self , library_name , source_list , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 10, "complexity": 2, "token_count": 85, "parameters": [ "self", "library_name", "source_list", "module_dirs", "temp_dir" ], "start_line": 322, "end_line": 343, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "dummy_fortran_files", "long_name": "dummy_fortran_files( self )", "filename": "build_flib.py", "nloc": 8, "complexity": 1, "token_count": 69, "parameters": [ "self" ], "start_line": 345, "end_line": 352, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "is_available", "long_name": "is_available( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 354, "end_line": 355, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_version", "long_name": "get_version( self )", "filename": "build_flib.py", "nloc": 10, "complexity": 4, "token_count": 66, "parameters": [ "self" ], "start_line": 357, "end_line": 375, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 19, "top_nesting_level": 1 }, { "name": "get_libraries", "long_name": "get_libraries( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self" ], "start_line": 377, "end_line": 378, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_library_dirs", "long_name": "get_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self" ], "start_line": 379, "end_line": 380, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 381, "end_line": 382, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 383, "end_line": 384, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 1, "complexity": 1, "token_count": 6, "parameters": [ "self" ], "start_line": 385, "end_line": 390, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "__str__", "long_name": "__str__( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 392, "end_line": 393, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 31, "complexity": 5, "token_count": 177, "parameters": [ "self", "fc", "f90c" ], "start_line": 401, "end_line": 439, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 6, "complexity": 3, "token_count": 27, "parameters": [ "self", "module_dirs" ], "start_line": 441, "end_line": 446, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 448, "end_line": 449, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 98, "parameters": [ "self", "fc", "f90c" ], "start_line": 462, "end_line": 484, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 6, "complexity": 3, "token_count": 27, "parameters": [ "self", "module_dirs" ], "start_line": 486, "end_line": 491, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "find_lib_dir", "long_name": "find_lib_dir( self )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 99, "parameters": [ "self" ], "start_line": 493, "end_line": 507, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 508, "end_line": 509, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 9, "parameters": [ "self" ], "start_line": 510, "end_line": 511, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 94, "parameters": [ "self", "fc", "f90c" ], "start_line": 519, "end_line": 537, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 19, "top_nesting_level": 1 }, { "name": "build_module_switch", "long_name": "build_module_switch( self , module_dirs )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 12, "parameters": [ "self", "module_dirs" ], "start_line": 539, "end_line": 541, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "find_lib_dir", "long_name": "find_lib_dir( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 542, "end_line": 544, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "get_runtime_library_dirs", "long_name": "get_runtime_library_dirs( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 11, "parameters": [ "self" ], "start_line": 545, "end_line": 546, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "get_extra_link_args", "long_name": "get_extra_link_args( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 8, "parameters": [ "self" ], "start_line": 547, "end_line": 548, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 16, "complexity": 5, "token_count": 103, "parameters": [ "self", "fc", "f90c" ], "start_line": 556, "end_line": 577, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 22, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 21, "complexity": 10, "token_count": 120, "parameters": [ "self" ], "start_line": 579, "end_line": 602, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 24, "top_nesting_level": 1 }, { "name": "find_lib_directories", "long_name": "find_lib_directories( self )", "filename": "build_flib.py", "nloc": 9, "complexity": 3, "token_count": 43, "parameters": [ "self" ], "start_line": 604, "end_line": 614, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 2, "token_count": 20, "parameters": [ "self" ], "start_line": 616, "end_line": 619, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "f90_compile", "long_name": "f90_compile( self , source_files , module_files , temp_dir = '' )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 17, "parameters": [ "self", "source_files", "module_files", "temp_dir" ], "start_line": 621, "end_line": 622, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 22, "complexity": 5, "token_count": 140, "parameters": [ "self", "fc", "f90c" ], "start_line": 631, "end_line": 659, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 29, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 15, "complexity": 7, "token_count": 85, "parameters": [ "self" ], "start_line": 661, "end_line": 675, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 678, "end_line": 679, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 4, "complexity": 2, "token_count": 31, "parameters": [ "self", "fc", "f90c" ], "start_line": 687, "end_line": 690, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 15, "complexity": 3, "token_count": 100, "parameters": [ "self", "fc", "f90c" ], "start_line": 698, "end_line": 717, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 10, "parameters": [ "self" ], "start_line": 719, "end_line": 721, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 723, "end_line": 724, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 20, "complexity": 5, "token_count": 128, "parameters": [ "self", "fc", "f90c" ], "start_line": 732, "end_line": 756, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 760, "end_line": 761, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 14, "complexity": 3, "token_count": 91, "parameters": [ "self", "fc", "f90c" ], "start_line": 768, "end_line": 790, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "get_opt", "long_name": "get_opt( self )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 10, "parameters": [ "self" ], "start_line": 792, "end_line": 794, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "get_linker_so", "long_name": "get_linker_so( self )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 13, "parameters": [ "self" ], "start_line": 796, "end_line": 798, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "match_extension", "long_name": "match_extension( files , ext )", "filename": "build_flib.py", "nloc": 3, "complexity": 1, "token_count": 44, "parameters": [ "files", "ext" ], "start_line": 801, "end_line": 803, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "get_f77_files", "long_name": "get_f77_files( files )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "files" ], "start_line": 805, "end_line": 806, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "get_f90_files", "long_name": "get_f90_files( files )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "files" ], "start_line": 808, "end_line": 809, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "get_fortran_files", "long_name": "get_fortran_files( files )", "filename": "build_flib.py", "nloc": 2, "complexity": 1, "token_count": 12, "parameters": [ "files" ], "start_line": 811, "end_line": 812, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 0 }, { "name": "find_fortran_compiler", "long_name": "find_fortran_compiler( vendor = None , fc = None , f90c = None )", "filename": "build_flib.py", "nloc": 11, "complexity": 5, "token_count": 59, "parameters": [ "vendor", "fc", "f90c" ], "start_line": 814, "end_line": 824, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "f_compile", "long_name": "f_compile( self , compiler , switches , source_files , module_dirs = None , temp_dir = '' )", "filename": "build_flib.py", "nloc": 15, "complexity": 4, "token_count": 103, "parameters": [ "self", "compiler", "switches", "source_files", "module_dirs", "temp_dir" ], "start_line": 282, "end_line": 296, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 } ], "nloc": 606, "complexity": 148, "token_count": 3483, "diff_parsed": { "added": [ "class FortranCompilerError (CCompilerError):", " \"\"\"Some compile/link operation failed.\"\"\"", "class FortranCompileError (FortranCompilerError):", " \"\"\"Failure to compile one or more Fortran source files.\"\"\"", "", " raise FortranCompileError, 'failure during compile'" ], "deleted": [ " raise ValueError, 'failure during compile'" ] } }, { "old_path": "scipy_distutils/command/run_f2py.py", "new_path": "scipy_distutils/command/run_f2py.py", "filename": "run_f2py.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -110,6 +110,8 @@ def f2py_sources (self, sources, ext):\n base = m.group('name')\n break\n f.close()\n+ if ext.name == 'untitled':\n+ ext.name = base\n if base != ext.name:\n # XXX: Should we do here more than just warn?\n self.warn('%s provides %s but this extension is %s' \\\n", "added_lines": 2, "deleted_lines": 0, "source_code": "\"\"\"distutils.command.run_f2py\n\nImplements the Distutils 'run_f2py' command.\n\"\"\"\n\n# created 2002/01/09, Pearu Peterson \n\n__revision__ = \"$Id$\"\n\nfrom distutils.dep_util import newer\nfrom scipy_distutils.core import Command\n\nimport re,os\n\nmodule_name_re = re.compile(r'\\s*python\\s*module\\s*(?P[\\w_]+)',re.I).match\nuser_module_name_re = re.compile(r'\\s*python\\s*module\\s*(?P[\\w_]*?__user__[\\w_]*)',re.I).match\nfortran_ext_re = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\\Z',re.I).match\n\nclass run_f2py(Command):\n\n description = \"\\\"run_f2py\\\" runs f2py that builds Fortran wrapper sources\"\\\n \"(C and occasionally Fortran).\"\n\n user_options = [('build-dir=', 'b',\n \"directory to build fortran wrappers to\"),\n ('debug-capi', None,\n \"generate C/API extensions with debugging code\"),\n ('no-wrap-functions', None,\n \"do not generate wrappers for Fortran functions,etc.\"),\n ('force', 'f',\n \"forcibly build everything (ignore file timestamps)\"),\n ]\n\n def initialize_options (self):\n self.build_dir = None\n self.debug_capi = None\n self.force = None\n self.no_wrap_functions = None\n self.f2py_options = []\n # initialize_options()\n\n\n def finalize_options (self):\n self.set_undefined_options('build',\n ('build_temp', 'build_dir'),\n ('force', 'force'))\n\n self.f2py_options.extend(['--build-dir',self.build_dir])\n\n if self.debug_capi is not None:\n self.f2py_options.append('--debug-capi')\n if self.no_wrap_functions is not None:\n self.f2py_options.append('--no-wrap-functions')\n\n # finalize_options()\n\n def run (self):\n if self.distribution.has_ext_modules():\n # XXX: might need also\n # build_flib = self.get_finalized_command('build_flib')\n # ...\n # for getting extra f2py_options that are specific to\n # a given fortran compiler.\n for ext in self.distribution.ext_modules:\n ext.sources = self.f2py_sources(ext.sources,ext)\n self.fortran_sources_to_flib(ext)\n # run()\n\n def f2py_sources (self, sources, ext):\n\n \"\"\"Walk the list of source files in 'sources', looking for f2py\n interface (.pyf) files. Run f2py on all that are found, and\n return a modified 'sources' list with f2py source files replaced\n by the generated C (or C++) and Fortran files.\n If 'sources' contains not .pyf files, then create a temporary\n one from the Fortran files in 'sources'.\n \"\"\"\n import string\n import f2py2e\n # f2py generates the following files for an extension module\n # with a name :\n # module.c\n # -f2pywrappers.f [occasionally]\n # In addition, /src/fortranobject.{c,h} are needed\n # for building f2py generated extension modules.\n # It is assumed that one pyf file contains defintions for exactly\n # one extension module.\n\n target_dir = self.build_dir\n \n new_sources = []\n f2py_sources = []\n fortran_sources = []\n f2py_targets = {}\n f2py_fortran_targets = {}\n target_ext = 'module.c'\n fortran_target_ext = '-f2pywrappers.f'\n\n for source in sources:\n (base, source_ext) = os.path.splitext(source)\n (source_dir, base) = os.path.split(base)\n if source_ext == \".pyf\": # f2py interface file\n # get extension module name\n f = open(source)\n for line in f.xreadlines():\n m = module_name_re(line)\n if m:\n if user_module_name_re(line): # skip *__user__* names\n continue\n base = m.group('name')\n break\n f.close()\n if ext.name == 'untitled':\n ext.name = base\n if base != ext.name:\n # XXX: Should we do here more than just warn?\n self.warn('%s provides %s but this extension is %s' \\\n % (source,`base`,`ext.name`))\n target_file = os.path.join(target_dir,base+target_ext)\n fortran_target_file = os.path.join(target_dir,base+fortran_target_ext)\n f2py_sources.append(source)\n f2py_targets[source] = target_file\n f2py_fortran_targets[source] = fortran_target_file\n elif fortran_ext_re(source_ext):\n fortran_sources.append(source) \n else:\n new_sources.append(source)\n\n if not (f2py_sources or fortran_sources):\n return new_sources\n\n # make sure the target dir exists\n from distutils.dir_util import mkpath\n mkpath(target_dir)\n\n if not f2py_sources:\n # creating a temporary pyf file from fortran sources\n pyf_target = os.path.join(target_dir,ext.name+'.pyf')\n pyf_target_file = os.path.join(target_dir,ext.name+target_ext)\n pyf_fortran_target_file = os.path.join(target_dir,ext.name+fortran_target_ext)\n f2py_opts2 = ['-m',ext.name,'-h',pyf_target,'--overwrite-signature']\n for source in fortran_sources:\n if newer(source,pyf_target) or self.force:\n self.announce(\"f2py-ing a new %s\" % (pyf_target))\n self.announce(\"f2py-opts: %s\" % string.join(f2py_opts2,' '))\n f2py2e.run_main(fortran_sources + f2py_opts2)\n break\n f2py_sources.append(pyf_target)\n f2py_targets[pyf_target] = pyf_target_file\n f2py_fortran_targets[pyf_target] = pyf_fortran_target_file\n\n new_sources.extend(fortran_sources)\n\n if len(f2py_sources) > 1:\n self.warn('Only one .pyf file can be used per Extension but got %s.'\\\n % (len(f2py_sources)))\n\n # a bit of a hack, but I think it'll work. Just include one of\n # the fortranobject.c files that was copied into most \n d = os.path.dirname(f2py2e.__file__)\n new_sources.append(os.path.join(d,'src','fortranobject.c'))\n ext.include_dirs.append(os.path.join(d,'src'))\n\n f2py_options = ext.f2py_options + self.f2py_options\n\n for source in f2py_sources:\n target = f2py_targets[source]\n fortran_target = f2py_fortran_targets[source]\n if newer(source,target) or self.force:\n self.announce(\"f2py-ing %s to %s\" % (source, target))\n self.announce(\"f2py-opts: %s\" % string.join(f2py_options,' '))\n f2py2e.run_main(f2py_options + [source])\n new_sources.append(target)\n if os.path.exists(fortran_target):\n new_sources.append(fortran_target)\n\n return new_sources\n\n # f2py_sources ()\n\n def fortran_sources_to_flib(self, ext):\n \"\"\"\n Extract fortran files from ext.sources and append them to\n fortran_libraries item having the same name as ext.\n \"\"\"\n sources = []\n f_files = []\n\n for file in ext.sources:\n if fortran_ext_re(file):\n f_files.append(file)\n else:\n sources.append(file)\n if not f_files:\n return\n\n ext.sources = sources\n\n if self.distribution.fortran_libraries is None:\n self.distribution.fortran_libraries = []\n fortran_libraries = self.distribution.fortran_libraries\n\n name = ext.name\n flib = None\n for n,d in fortran_libraries:\n if n == name:\n flib = d\n break\n if flib is None:\n flib = {'sources':[]}\n fortran_libraries.append((name,flib))\n\n flib['sources'].extend(f_files)\n \n# class run_f2py\n", "source_code_before": "\"\"\"distutils.command.run_f2py\n\nImplements the Distutils 'run_f2py' command.\n\"\"\"\n\n# created 2002/01/09, Pearu Peterson \n\n__revision__ = \"$Id$\"\n\nfrom distutils.dep_util import newer\nfrom scipy_distutils.core import Command\n\nimport re,os\n\nmodule_name_re = re.compile(r'\\s*python\\s*module\\s*(?P[\\w_]+)',re.I).match\nuser_module_name_re = re.compile(r'\\s*python\\s*module\\s*(?P[\\w_]*?__user__[\\w_]*)',re.I).match\nfortran_ext_re = re.compile(r'.*[.](f90|f95|f77|for|ftn|f)\\Z',re.I).match\n\nclass run_f2py(Command):\n\n description = \"\\\"run_f2py\\\" runs f2py that builds Fortran wrapper sources\"\\\n \"(C and occasionally Fortran).\"\n\n user_options = [('build-dir=', 'b',\n \"directory to build fortran wrappers to\"),\n ('debug-capi', None,\n \"generate C/API extensions with debugging code\"),\n ('no-wrap-functions', None,\n \"do not generate wrappers for Fortran functions,etc.\"),\n ('force', 'f',\n \"forcibly build everything (ignore file timestamps)\"),\n ]\n\n def initialize_options (self):\n self.build_dir = None\n self.debug_capi = None\n self.force = None\n self.no_wrap_functions = None\n self.f2py_options = []\n # initialize_options()\n\n\n def finalize_options (self):\n self.set_undefined_options('build',\n ('build_temp', 'build_dir'),\n ('force', 'force'))\n\n self.f2py_options.extend(['--build-dir',self.build_dir])\n\n if self.debug_capi is not None:\n self.f2py_options.append('--debug-capi')\n if self.no_wrap_functions is not None:\n self.f2py_options.append('--no-wrap-functions')\n\n # finalize_options()\n\n def run (self):\n if self.distribution.has_ext_modules():\n # XXX: might need also\n # build_flib = self.get_finalized_command('build_flib')\n # ...\n # for getting extra f2py_options that are specific to\n # a given fortran compiler.\n for ext in self.distribution.ext_modules:\n ext.sources = self.f2py_sources(ext.sources,ext)\n self.fortran_sources_to_flib(ext)\n # run()\n\n def f2py_sources (self, sources, ext):\n\n \"\"\"Walk the list of source files in 'sources', looking for f2py\n interface (.pyf) files. Run f2py on all that are found, and\n return a modified 'sources' list with f2py source files replaced\n by the generated C (or C++) and Fortran files.\n If 'sources' contains not .pyf files, then create a temporary\n one from the Fortran files in 'sources'.\n \"\"\"\n import string\n import f2py2e\n # f2py generates the following files for an extension module\n # with a name :\n # module.c\n # -f2pywrappers.f [occasionally]\n # In addition, /src/fortranobject.{c,h} are needed\n # for building f2py generated extension modules.\n # It is assumed that one pyf file contains defintions for exactly\n # one extension module.\n\n target_dir = self.build_dir\n \n new_sources = []\n f2py_sources = []\n fortran_sources = []\n f2py_targets = {}\n f2py_fortran_targets = {}\n target_ext = 'module.c'\n fortran_target_ext = '-f2pywrappers.f'\n\n for source in sources:\n (base, source_ext) = os.path.splitext(source)\n (source_dir, base) = os.path.split(base)\n if source_ext == \".pyf\": # f2py interface file\n # get extension module name\n f = open(source)\n for line in f.xreadlines():\n m = module_name_re(line)\n if m:\n if user_module_name_re(line): # skip *__user__* names\n continue\n base = m.group('name')\n break\n f.close()\n if base != ext.name:\n # XXX: Should we do here more than just warn?\n self.warn('%s provides %s but this extension is %s' \\\n % (source,`base`,`ext.name`))\n target_file = os.path.join(target_dir,base+target_ext)\n fortran_target_file = os.path.join(target_dir,base+fortran_target_ext)\n f2py_sources.append(source)\n f2py_targets[source] = target_file\n f2py_fortran_targets[source] = fortran_target_file\n elif fortran_ext_re(source_ext):\n fortran_sources.append(source) \n else:\n new_sources.append(source)\n\n if not (f2py_sources or fortran_sources):\n return new_sources\n\n # make sure the target dir exists\n from distutils.dir_util import mkpath\n mkpath(target_dir)\n\n if not f2py_sources:\n # creating a temporary pyf file from fortran sources\n pyf_target = os.path.join(target_dir,ext.name+'.pyf')\n pyf_target_file = os.path.join(target_dir,ext.name+target_ext)\n pyf_fortran_target_file = os.path.join(target_dir,ext.name+fortran_target_ext)\n f2py_opts2 = ['-m',ext.name,'-h',pyf_target,'--overwrite-signature']\n for source in fortran_sources:\n if newer(source,pyf_target) or self.force:\n self.announce(\"f2py-ing a new %s\" % (pyf_target))\n self.announce(\"f2py-opts: %s\" % string.join(f2py_opts2,' '))\n f2py2e.run_main(fortran_sources + f2py_opts2)\n break\n f2py_sources.append(pyf_target)\n f2py_targets[pyf_target] = pyf_target_file\n f2py_fortran_targets[pyf_target] = pyf_fortran_target_file\n\n new_sources.extend(fortran_sources)\n\n if len(f2py_sources) > 1:\n self.warn('Only one .pyf file can be used per Extension but got %s.'\\\n % (len(f2py_sources)))\n\n # a bit of a hack, but I think it'll work. Just include one of\n # the fortranobject.c files that was copied into most \n d = os.path.dirname(f2py2e.__file__)\n new_sources.append(os.path.join(d,'src','fortranobject.c'))\n ext.include_dirs.append(os.path.join(d,'src'))\n\n f2py_options = ext.f2py_options + self.f2py_options\n\n for source in f2py_sources:\n target = f2py_targets[source]\n fortran_target = f2py_fortran_targets[source]\n if newer(source,target) or self.force:\n self.announce(\"f2py-ing %s to %s\" % (source, target))\n self.announce(\"f2py-opts: %s\" % string.join(f2py_options,' '))\n f2py2e.run_main(f2py_options + [source])\n new_sources.append(target)\n if os.path.exists(fortran_target):\n new_sources.append(fortran_target)\n\n return new_sources\n\n # f2py_sources ()\n\n def fortran_sources_to_flib(self, ext):\n \"\"\"\n Extract fortran files from ext.sources and append them to\n fortran_libraries item having the same name as ext.\n \"\"\"\n sources = []\n f_files = []\n\n for file in ext.sources:\n if fortran_ext_re(file):\n f_files.append(file)\n else:\n sources.append(file)\n if not f_files:\n return\n\n ext.sources = sources\n\n if self.distribution.fortran_libraries is None:\n self.distribution.fortran_libraries = []\n fortran_libraries = self.distribution.fortran_libraries\n\n name = ext.name\n flib = None\n for n,d in fortran_libraries:\n if n == name:\n flib = d\n break\n if flib is None:\n flib = {'sources':[]}\n fortran_libraries.append((name,flib))\n\n flib['sources'].extend(f_files)\n \n# class run_f2py\n", "methods": [ { "name": "initialize_options", "long_name": "initialize_options( self )", "filename": "run_f2py.py", "nloc": 6, "complexity": 1, "token_count": 31, "parameters": [ "self" ], "start_line": 34, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "finalize_options", "long_name": "finalize_options( self )", "filename": "run_f2py.py", "nloc": 9, "complexity": 3, "token_count": 69, "parameters": [ "self" ], "start_line": 43, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "run", "long_name": "run( self )", "filename": "run_f2py.py", "nloc": 5, "complexity": 3, "token_count": 43, "parameters": [ "self" ], "start_line": 57, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "f2py_sources", "long_name": "f2py_sources( self , sources , ext )", "filename": "run_f2py.py", "nloc": 75, "complexity": 20, "token_count": 563, "parameters": [ "self", "sources", "ext" ], "start_line": 69, "end_line": 177, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 109, "top_nesting_level": 1 }, { "name": "fortran_sources_to_flib", "long_name": "fortran_sources_to_flib( self , ext )", "filename": "run_f2py.py", "nloc": 24, "complexity": 8, "token_count": 133, "parameters": [ "self", "ext" ], "start_line": 181, "end_line": 213, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 33, "top_nesting_level": 1 } ], "methods_before": [ { "name": "initialize_options", "long_name": "initialize_options( self )", "filename": "run_f2py.py", "nloc": 6, "complexity": 1, "token_count": 31, "parameters": [ "self" ], "start_line": 34, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "finalize_options", "long_name": "finalize_options( self )", "filename": "run_f2py.py", "nloc": 9, "complexity": 3, "token_count": 69, "parameters": [ "self" ], "start_line": 43, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "run", "long_name": "run( self )", "filename": "run_f2py.py", "nloc": 5, "complexity": 3, "token_count": 43, "parameters": [ "self" ], "start_line": 57, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "f2py_sources", "long_name": "f2py_sources( self , sources , ext )", "filename": "run_f2py.py", "nloc": 73, "complexity": 19, "token_count": 551, "parameters": [ "self", "sources", "ext" ], "start_line": 69, "end_line": 175, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 107, "top_nesting_level": 1 }, { "name": "fortran_sources_to_flib", "long_name": "fortran_sources_to_flib( self , ext )", "filename": "run_f2py.py", "nloc": 24, "complexity": 8, "token_count": 133, "parameters": [ "self", "ext" ], "start_line": 179, "end_line": 211, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 33, "top_nesting_level": 1 } ], "changed_methods": [ { "name": "f2py_sources", "long_name": "f2py_sources( self , sources , ext )", "filename": "run_f2py.py", "nloc": 75, "complexity": 20, "token_count": 563, "parameters": [ "self", "sources", "ext" ], "start_line": 69, "end_line": 177, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 109, "top_nesting_level": 1 } ], "nloc": 142, "complexity": 35, "token_count": 956, "diff_parsed": { "added": [ " if ext.name == 'untitled':", " ext.name = base" ], "deleted": [] } } ] }, { "hash": "ec1bba279c2b78aa7192a1b047e426b917ac9479", "msg": "added keyword arguments to blitz() so that it can handle distutils arguments just like inline()\n\nconverted all exceptions to call throw_error(). throw_error(exception,msg) will set the Python exception values and then through an integer exception. This is the only one that seems to work on Mandrake. Gordon McMillan says it happens on other platforms also when the python has been linked with a C compiler instead of a C++ compiler (which is almost always the case).", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T01:43:04+00:00", "author_timezone": 0, "committer_date": "2002-01-17T01:43:04+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "79cd95adf1c70d464b266d1fd84e1d98781117b1" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 29, "insertions": 44, "lines": 73, "files": 9, "dmm_unit_size": 0.0, "dmm_unit_complexity": 0.0, "dmm_unit_interfacing": 0.0, "modified_files": [ { "old_path": "weave/blitz_tools.py", "new_path": "weave/blitz_tools.py", "filename": "blitz_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -51,7 +51,7 @@\n except: \n pass \n \n-def blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0):\n+def blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0,**kw):\n # this could call inline, but making a copy of the\n # code here is more efficient for several reasons.\n global function_catalog\n@@ -96,7 +96,8 @@ def blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0):\n global_dict,module_dir,\n compiler='gcc',auto_downcast=1,\n verbose = verbose,\n- type_factories = blitz_type_factories)\n+ type_factories = blitz_type_factories,\n+ **kw)\n function_catalog.add_function(expr,func,module_dir)\n try: \n results = attempt_function_call(expr,local_dict,global_dict)\n", "added_lines": 3, "deleted_lines": 2, "source_code": "import parser\nimport string\nimport copy\nimport os,sys\nimport ast_tools\nimport token,symbol\nimport slice_handler\nimport size_check\n\nfrom ast_tools import *\n\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \n \nfrom types import *\n\nimport inline_tools\nfrom inline_tools import attempt_function_call\nfunction_catalog = inline_tools.function_catalog\nfunction_cache = inline_tools.function_cache\n\n# this is pretty much the same as the default factories.\n# We've just replaced the array specification with the blitz\n# specification\nimport base_spec\nimport scalar_spec\nimport sequence_spec\nimport common_spec\nfrom blitz_spec import array_specification\nblitz_type_factories = [sequence_spec.string_specification(),\n sequence_spec.list_specification(),\n sequence_spec.dict_specification(),\n sequence_spec.tuple_specification(),\n scalar_spec.int_specification(),\n scalar_spec.float_specification(),\n scalar_spec.complex_specification(),\n common_spec.file_specification(),\n common_spec.callable_specification(),\n array_specification()]\n #common_spec.instance_specification(), \n #common_spec.module_specification()]\n\ntry: \n # this is currently safe because it doesn't import wxPython.\n import wx_spec\n default_type_factories.append(wx_spec.wx_specification())\nexcept: \n pass \n \ndef blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0,**kw):\n # this could call inline, but making a copy of the\n # code here is more efficient for several reasons.\n global function_catalog\n \n # this grabs the local variables from the *previous* call\n # frame -- that is the locals from the function that called\n # inline.\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n\n # 1. Check the sizes of the arrays and make sure they are compatible.\n # This is expensive, so unsetting the check_size flag can save a lot\n # of time. It also can cause core-dumps if the sizes of the inputs \n # aren't compatible. \n if check_size and not size_check.check_expr(expr,local_dict,global_dict):\n raise 'inputs failed to pass size check.'\n \n # 2. try local cache \n try:\n results = apply(function_cache[expr],(local_dict,global_dict))\n return results\n except: \n pass\n try:\n results = attempt_function_call(expr,local_dict,global_dict)\n # 3. build the function \n except ValueError:\n # This section is pretty much the only difference \n # between blitz and inline\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n expr_code = ast_to_blitz_expr(ast_list)\n arg_names = harvest_variables(ast_list)\n module_dir = global_dict.get('__file__',None)\n #func = inline_tools.compile_function(expr_code,arg_names,\n # local_dict,global_dict,\n # module_dir,auto_downcast = 1)\n func = inline_tools.compile_function(expr_code,arg_names,local_dict, \n global_dict,module_dir,\n compiler='gcc',auto_downcast=1,\n verbose = verbose,\n type_factories = blitz_type_factories,\n **kw)\n function_catalog.add_function(expr,func,module_dir)\n try: \n results = attempt_function_call(expr,local_dict,global_dict)\n except ValueError: \n print 'warning: compilation failed. Executing as python code'\n exec expr in global_dict, local_dict\n \ndef ast_to_blitz_expr(ast_seq):\n \"\"\" Convert an ast_sequence to a blitz expression.\n \"\"\"\n \n # Don't overwrite orignal sequence in call to transform slices.\n ast_seq = copy.deepcopy(ast_seq) \n slice_handler.transform_slices(ast_seq)\n \n # Build the actual program statement from ast_seq\n expr = ast_tools.ast_to_string(ast_seq)\n \n # Now find and replace specific symbols to convert this to\n # a blitz++ compatible statement.\n # I'm doing this with string replacement here. It could\n # also be done on the actual ast tree (and probably should from\n # a purest standpoint...).\n \n # this one isn't necessary but it helps code readability\n # and compactness. It requires that \n # Range _all = blitz::Range::all();\n # be included in the generated code. \n # These could all alternatively be done to the ast in\n # build_slice_atom()\n expr = string.replace(expr,'slice(_beg,_end)', '_all' ) \n expr = string.replace(expr,'slice', 'blitz::Range' )\n expr = string.replace(expr,'[','(')\n expr = string.replace(expr,']', ')' )\n expr = string.replace(expr,'_stp', '1' )\n \n # Instead of blitz::fromStart and blitz::toEnd. This requires\n # the following in the generated code.\n # Range _beg = blitz::fromStart;\n # Range _end = blitz::toEnd;\n #expr = string.replace(expr,'_beg', 'blitz::fromStart' )\n #expr = string.replace(expr,'_end', 'blitz::toEnd' )\n \n return expr + ';\\n'\n\ndef test_function():\n from code_blocks import module_header\n\n expr = \"ex[:,1:,1:] = k + ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,1:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n #ast = parser.suite('a = (b + c) * sin(d)')\n ast = parser.suite(expr)\n k = 1.\n ex = ones((1,1,1),typecode=Float32)\n ca_x = ones((1,1,1),typecode=Float32)\n cb_y_x = ones((1,1,1),typecode=Float32)\n cb_z_x = ones((1,1,1),typecode=Float32)\n hz = ones((1,1,1),typecode=Float32)\n hy = ones((1,1,1),typecode=Float32)\n blitz(expr)\n \"\"\"\n ast_list = ast.tolist()\n \n expr_code = ast_to_blitz_expr(ast_list)\n arg_list = harvest_variables(ast_list)\n arg_specs = assign_variable_types(arg_list,locals())\n \n func,template_types = create_function('test_function',expr_code,arg_list,arg_specs)\n init,used_names = create_module_init('compile_sample','test_function',template_types)\n #wrapper = create_wrapper(mod_name,func_name,used_names)\n return string.join( [module_header,func,init],'\\n')\n \"\"\"\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\nif __name__ == \"__main__\":\n test_function()", "source_code_before": "import parser\nimport string\nimport copy\nimport os,sys\nimport ast_tools\nimport token,symbol\nimport slice_handler\nimport size_check\n\nfrom ast_tools import *\n\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \n \nfrom types import *\n\nimport inline_tools\nfrom inline_tools import attempt_function_call\nfunction_catalog = inline_tools.function_catalog\nfunction_cache = inline_tools.function_cache\n\n# this is pretty much the same as the default factories.\n# We've just replaced the array specification with the blitz\n# specification\nimport base_spec\nimport scalar_spec\nimport sequence_spec\nimport common_spec\nfrom blitz_spec import array_specification\nblitz_type_factories = [sequence_spec.string_specification(),\n sequence_spec.list_specification(),\n sequence_spec.dict_specification(),\n sequence_spec.tuple_specification(),\n scalar_spec.int_specification(),\n scalar_spec.float_specification(),\n scalar_spec.complex_specification(),\n common_spec.file_specification(),\n common_spec.callable_specification(),\n array_specification()]\n #common_spec.instance_specification(), \n #common_spec.module_specification()]\n\ntry: \n # this is currently safe because it doesn't import wxPython.\n import wx_spec\n default_type_factories.append(wx_spec.wx_specification())\nexcept: \n pass \n \ndef blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0):\n # this could call inline, but making a copy of the\n # code here is more efficient for several reasons.\n global function_catalog\n \n # this grabs the local variables from the *previous* call\n # frame -- that is the locals from the function that called\n # inline.\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n\n # 1. Check the sizes of the arrays and make sure they are compatible.\n # This is expensive, so unsetting the check_size flag can save a lot\n # of time. It also can cause core-dumps if the sizes of the inputs \n # aren't compatible. \n if check_size and not size_check.check_expr(expr,local_dict,global_dict):\n raise 'inputs failed to pass size check.'\n \n # 2. try local cache \n try:\n results = apply(function_cache[expr],(local_dict,global_dict))\n return results\n except: \n pass\n try:\n results = attempt_function_call(expr,local_dict,global_dict)\n # 3. build the function \n except ValueError:\n # This section is pretty much the only difference \n # between blitz and inline\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n expr_code = ast_to_blitz_expr(ast_list)\n arg_names = harvest_variables(ast_list)\n module_dir = global_dict.get('__file__',None)\n #func = inline_tools.compile_function(expr_code,arg_names,\n # local_dict,global_dict,\n # module_dir,auto_downcast = 1)\n func = inline_tools.compile_function(expr_code,arg_names,local_dict, \n global_dict,module_dir,\n compiler='gcc',auto_downcast=1,\n verbose = verbose,\n type_factories = blitz_type_factories)\n function_catalog.add_function(expr,func,module_dir)\n try: \n results = attempt_function_call(expr,local_dict,global_dict)\n except ValueError: \n print 'warning: compilation failed. Executing as python code'\n exec expr in global_dict, local_dict\n \ndef ast_to_blitz_expr(ast_seq):\n \"\"\" Convert an ast_sequence to a blitz expression.\n \"\"\"\n \n # Don't overwrite orignal sequence in call to transform slices.\n ast_seq = copy.deepcopy(ast_seq) \n slice_handler.transform_slices(ast_seq)\n \n # Build the actual program statement from ast_seq\n expr = ast_tools.ast_to_string(ast_seq)\n \n # Now find and replace specific symbols to convert this to\n # a blitz++ compatible statement.\n # I'm doing this with string replacement here. It could\n # also be done on the actual ast tree (and probably should from\n # a purest standpoint...).\n \n # this one isn't necessary but it helps code readability\n # and compactness. It requires that \n # Range _all = blitz::Range::all();\n # be included in the generated code. \n # These could all alternatively be done to the ast in\n # build_slice_atom()\n expr = string.replace(expr,'slice(_beg,_end)', '_all' ) \n expr = string.replace(expr,'slice', 'blitz::Range' )\n expr = string.replace(expr,'[','(')\n expr = string.replace(expr,']', ')' )\n expr = string.replace(expr,'_stp', '1' )\n \n # Instead of blitz::fromStart and blitz::toEnd. This requires\n # the following in the generated code.\n # Range _beg = blitz::fromStart;\n # Range _end = blitz::toEnd;\n #expr = string.replace(expr,'_beg', 'blitz::fromStart' )\n #expr = string.replace(expr,'_end', 'blitz::toEnd' )\n \n return expr + ';\\n'\n\ndef test_function():\n from code_blocks import module_header\n\n expr = \"ex[:,1:,1:] = k + ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,1:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n #ast = parser.suite('a = (b + c) * sin(d)')\n ast = parser.suite(expr)\n k = 1.\n ex = ones((1,1,1),typecode=Float32)\n ca_x = ones((1,1,1),typecode=Float32)\n cb_y_x = ones((1,1,1),typecode=Float32)\n cb_z_x = ones((1,1,1),typecode=Float32)\n hz = ones((1,1,1),typecode=Float32)\n hy = ones((1,1,1),typecode=Float32)\n blitz(expr)\n \"\"\"\n ast_list = ast.tolist()\n \n expr_code = ast_to_blitz_expr(ast_list)\n arg_list = harvest_variables(ast_list)\n arg_specs = assign_variable_types(arg_list,locals())\n \n func,template_types = create_function('test_function',expr_code,arg_list,arg_specs)\n init,used_names = create_module_init('compile_sample','test_function',template_types)\n #wrapper = create_wrapper(mod_name,func_name,used_names)\n return string.join( [module_header,func,init],'\\n')\n \"\"\"\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\nif __name__ == \"__main__\":\n test_function()", "methods": [ { "name": "blitz", "long_name": "blitz( expr , local_dict = None , global_dict = None , check_size = 1 , verbose = 0 , ** kw )", "filename": "blitz_tools.py", "nloc": 34, "complexity": 8, "token_count": 214, "parameters": [ "expr", "local_dict", "global_dict", "check_size", "verbose", "kw" ], "start_line": 54, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 53, "top_nesting_level": 0 }, { "name": "ast_to_blitz_expr", "long_name": "ast_to_blitz_expr( ast_seq )", "filename": "blitz_tools.py", "nloc": 10, "complexity": 1, "token_count": 92, "parameters": [ "ast_seq" ], "start_line": 108, "end_line": 144, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 37, "top_nesting_level": 0 }, { "name": "test_function", "long_name": "test_function( )", "filename": "blitz_tools.py", "nloc": 26, "complexity": 1, "token_count": 128, "parameters": [], "start_line": 146, "end_line": 173, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 28, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "blitz_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 174, "end_line": 176, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "blitz_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 178, "end_line": 180, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "blitz", "long_name": "blitz( expr , local_dict = None , global_dict = None , check_size = 1 , verbose = 0 )", "filename": "blitz_tools.py", "nloc": 33, "complexity": 8, "token_count": 208, "parameters": [ "expr", "local_dict", "global_dict", "check_size", "verbose" ], "start_line": 54, "end_line": 105, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 52, "top_nesting_level": 0 }, { "name": "ast_to_blitz_expr", "long_name": "ast_to_blitz_expr( ast_seq )", "filename": "blitz_tools.py", "nloc": 10, "complexity": 1, "token_count": 92, "parameters": [ "ast_seq" ], "start_line": 107, "end_line": 143, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 37, "top_nesting_level": 0 }, { "name": "test_function", "long_name": "test_function( )", "filename": "blitz_tools.py", "nloc": 26, "complexity": 1, "token_count": 128, "parameters": [], "start_line": 145, "end_line": 172, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 28, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "blitz_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 173, "end_line": 175, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "blitz_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 177, "end_line": 179, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "blitz", "long_name": "blitz( expr , local_dict = None , global_dict = None , check_size = 1 , verbose = 0 )", "filename": "blitz_tools.py", "nloc": 33, "complexity": 8, "token_count": 208, "parameters": [ "expr", "local_dict", "global_dict", "check_size", "verbose" ], "start_line": 54, "end_line": 105, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 52, "top_nesting_level": 0 }, { "name": "blitz", "long_name": "blitz( expr , local_dict = None , global_dict = None , check_size = 1 , verbose = 0 , ** kw )", "filename": "blitz_tools.py", "nloc": 34, "complexity": 8, "token_count": 214, "parameters": [ "expr", "local_dict", "global_dict", "check_size", "verbose", "kw" ], "start_line": 54, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 53, "top_nesting_level": 0 } ], "nloc": 117, "complexity": 12, "token_count": 623, "diff_parsed": { "added": [ "def blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0,**kw):", " type_factories = blitz_type_factories,", " **kw)" ], "deleted": [ "def blitz(expr,local_dict=None, global_dict=None,check_size=1,verbose=0):", " type_factories = blitz_type_factories)" ] } }, { "old_path": "weave/code_blocks.py", "new_path": "weave/code_blocks.py", "filename": "code_blocks.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -20,8 +20,7 @@\n \n // Make sure input is an array.\n if (!PyArray_Check(py_obj))\n- throw PWException(PyExc_TypeError,\n- \"Input array *name* must be an array.\");\n+ throw_error(PyExc_TypeError,\"Input array *name* must be an array.\");\n \n arr_obj = (PyArrayObject*) py_obj;\n \n@@ -31,8 +30,8 @@\n // This should be more explicit:\n // Put the desired and actual type in the message.\n // printf(\"%d,%d\",arr_obj->descr->type_num,numeric_type);\n- throw PWException(PyExc_TypeError,\n- \"Input array *name* is the wrong numeric type.\");\n+ throw_error(PyExc_TypeError,\n+ \"Input array *name* is the wrong numeric type.\");\n }\n \n // Make sure input has correct rank (defined as number of dimensions).\n@@ -43,8 +42,8 @@\n {\n // This should be more explicit:\n // Put the desired and actual dimensionality in message.\n- throw PWException(PyExc_TypeError,\n- \"Input array *name* has wrong number of dimensions.\");\n+ throw_error(PyExc_TypeError,\n+ \"Input array *name* has wrong number of dimensions.\");\n } \n // check the size of arrays. Acutally, the size of the \"views\" really\n // needs checking -- not the arrays.\n", "added_lines": 5, "deleted_lines": 6, "source_code": "module_header = \\\n\"\"\" \n// blitz must be first, or you get have issues with isnan defintion.\n#include \n\n#include \"Python.h\" \n#include \"Numeric/arrayobject.h\" \n\n// Use Exception stuff from SCXX\n#include \"PWOBase.h\" \n\n#include \n#include \n#include \n\nstatic PyArrayObject* obj_to_numpy(PyObject* py_obj, char* name, \n int Ndims, int numeric_type )\n{\n PyArrayObject* arr_obj = NULL;\n\n // Make sure input is an array.\n if (!PyArray_Check(py_obj))\n throw_error(PyExc_TypeError,\"Input array *name* must be an array.\");\n\n arr_obj = (PyArrayObject*) py_obj;\n \n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n // This should be more explicit:\n // Put the desired and actual type in the message.\n // printf(\"%d,%d\",arr_obj->descr->type_num,numeric_type);\n throw_error(PyExc_TypeError,\n \"Input array *name* is the wrong numeric type.\");\n }\n \n // Make sure input has correct rank (defined as number of dimensions).\n // Currently, all arrays must have the same shape.\n // Broadcasting is not supported.\n // ...\n if (arr_obj->nd != Ndims)\n {\n // This should be more explicit:\n // Put the desired and actual dimensionality in message.\n throw_error(PyExc_TypeError,\n \"Input array *name* has wrong number of dimensions.\");\n } \n // check the size of arrays. Acutally, the size of the \"views\" really\n // needs checking -- not the arrays.\n // ...\n \n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return arr_obj;\n}\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_INT};};\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array py_to_blitz(PyObject* py_obj,char* name)\n{\n\n PyArrayObject* arr_obj = obj_to_numpy(py_obj,name,N,py_type::code);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n return (int) PyLong_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n return (long) PyLong_AsLong(py_obj);\n}\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) PyFloat_AsDouble(py_obj);\n}\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_RealAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_RealAsDouble(py_obj)); \n}\n\"\"\" ", "source_code_before": "module_header = \\\n\"\"\" \n// blitz must be first, or you get have issues with isnan defintion.\n#include \n\n#include \"Python.h\" \n#include \"Numeric/arrayobject.h\" \n\n// Use Exception stuff from SCXX\n#include \"PWOBase.h\" \n\n#include \n#include \n#include \n\nstatic PyArrayObject* obj_to_numpy(PyObject* py_obj, char* name, \n int Ndims, int numeric_type )\n{\n PyArrayObject* arr_obj = NULL;\n\n // Make sure input is an array.\n if (!PyArray_Check(py_obj))\n throw PWException(PyExc_TypeError,\n \"Input array *name* must be an array.\");\n\n arr_obj = (PyArrayObject*) py_obj;\n \n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n // This should be more explicit:\n // Put the desired and actual type in the message.\n // printf(\"%d,%d\",arr_obj->descr->type_num,numeric_type);\n throw PWException(PyExc_TypeError,\n \"Input array *name* is the wrong numeric type.\");\n }\n \n // Make sure input has correct rank (defined as number of dimensions).\n // Currently, all arrays must have the same shape.\n // Broadcasting is not supported.\n // ...\n if (arr_obj->nd != Ndims)\n {\n // This should be more explicit:\n // Put the desired and actual dimensionality in message.\n throw PWException(PyExc_TypeError,\n \"Input array *name* has wrong number of dimensions.\");\n } \n // check the size of arrays. Acutally, the size of the \"views\" really\n // needs checking -- not the arrays.\n // ...\n \n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return arr_obj;\n}\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_INT};};\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array py_to_blitz(PyObject* py_obj,char* name)\n{\n\n PyArrayObject* arr_obj = obj_to_numpy(py_obj,name,N,py_type::code);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n return (int) PyLong_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n return (long) PyLong_AsLong(py_obj);\n}\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) PyFloat_AsDouble(py_obj);\n}\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_RealAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_RealAsDouble(py_obj)); \n}\n\"\"\" ", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 134, "complexity": 0, "token_count": 4, "diff_parsed": { "added": [ " throw_error(PyExc_TypeError,\"Input array *name* must be an array.\");", " throw_error(PyExc_TypeError,", " \"Input array *name* is the wrong numeric type.\");", " throw_error(PyExc_TypeError,", " \"Input array *name* has wrong number of dimensions.\");" ], "deleted": [ " throw PWException(PyExc_TypeError,", " \"Input array *name* must be an array.\");", " throw PWException(PyExc_TypeError,", " \"Input array *name* is the wrong numeric type.\");", " throw PWException(PyExc_TypeError,", " \"Input array *name* has wrong number of dimensions.\");" ] } }, { "old_path": "weave/conversion_code.py", "new_path": "weave/conversion_code.py", "filename": "conversion_code.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -47,12 +47,18 @@\n return \"unkown type\";\n }\n \n+void throw_error(PyObject* py_obj, const char* msg)\n+{\n+ PyErr_SetString(exc, msg);\n+ throw 1;\n+}\n+\n void handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n {\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n- throw Py::TypeError(msg);\n+ throw_error(PyExc_TypeError,msg); \n }\n \n void handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n@@ -60,7 +66,7 @@\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n- throw Py::TypeError(msg);\n+ throw_error(PyExc_TypeError,msg);\n }\n \n \"\"\"\n", "added_lines": 8, "deleted_lines": 2, "source_code": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* py_obj, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nFILE* convert_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nFILE* py_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nPyObject* convert_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nstatic int convert_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long convert_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double convert_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex convert_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "source_code_before": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw Py::TypeError(msg);\n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw Py::TypeError(msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nFILE* convert_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nFILE* py_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nPyObject* convert_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nstatic int convert_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long convert_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double convert_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex convert_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 381, "complexity": 0, "token_count": 33, "diff_parsed": { "added": [ "void throw_error(PyObject* py_obj, const char* msg)", "{", " PyErr_SetString(exc, msg);", " throw 1;", "}", "", " throw_error(PyExc_TypeError,msg);", " throw_error(PyExc_TypeError,msg);" ], "deleted": [ " throw Py::TypeError(msg);", " throw Py::TypeError(msg);" ] } }, { "old_path": "weave/ext_tools.py", "new_path": "weave/ext_tools.py", "filename": "ext_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -7,6 +7,7 @@\n import scalar_spec\n import sequence_spec\n import common_spec\n+import catalog \n \n default_type_factories = [scalar_spec.int_specification(),\n scalar_spec.float_specification(),\n@@ -146,7 +147,7 @@ def function_code(self):\n function_code + \\\n indent(dict_code,4) + \\\n \"\\n} \\n\"\n- catch_code = \"catch( Py::Exception& e) \\n\" \\\n+ catch_code = \"catch(...) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n@@ -337,7 +338,8 @@ def compile(self,location='.',compiler=None, verbose = 0, **kw):\n file = self.generate_file(location=location)\n # This is needed so that files build correctly even when different\n # versions of Python are running around.\n- import catalog \n+ # Imported at beginning of file now to help with test paths.\n+ # import catalog \n #temp = catalog.default_temp_dir()\n # for speed, build in the machines temp directory\n temp = catalog.intermediate_dir()\n", "added_lines": 4, "deleted_lines": 2, "source_code": "import os, sys\nimport string, re\n\nimport build_tools\n\nimport base_spec\nimport scalar_spec\nimport sequence_spec\nimport common_spec\nimport catalog \n\ndefault_type_factories = [scalar_spec.int_specification(),\n scalar_spec.float_specification(),\n scalar_spec.complex_specification(),\n sequence_spec.string_specification(),\n sequence_spec.list_specification(),\n sequence_spec.dict_specification(),\n sequence_spec.tuple_specification(),\n common_spec.file_specification(),\n common_spec.callable_specification()]\n #common_spec.instance_specification(), \n #common_spec.module_specification()]\n\ntry: \n from standard_array_spec import array_specification\n default_type_factories.append(array_specification())\nexcept: \n pass \n\ntry: \n # this is currently safe because it doesn't import wxPython.\n import wx_spec\n default_type_factories.append(wx_spec.wx_specification())\nexcept: \n pass \n\nclass ext_function_from_specs:\n def __init__(self,name,code_block,arg_specs):\n self.name = name\n self.arg_specs = base_spec.arg_spec_list(arg_specs)\n self.code_block = code_block\n self.compiler = ''\n self.customize = base_info.custom_info()\n \n def header_code(self):\n pass\n\n def function_declaration_code(self):\n code = 'static PyObject* %s(PyObject*self, PyObject* args,' \\\n ' PyObject* kywds)\\n{\\n'\n return code % self.name\n\n def template_declaration_code(self):\n code = 'template\\n' \\\n 'static PyObject* %s(PyObject*self, PyObject* args,' \\\n ' PyObject* kywds)\\n{\\n'\n return code % self.name\n\n #def cpp_function_declaration_code(self):\n # pass\n #def cpp_function_call_code(self):\n #s pass\n \n def parse_tuple_code(self):\n \"\"\" Create code block for PyArg_ParseTuple. Variable declarations\n for all PyObjects are done also.\n \n This code got a lot uglier when I added local_dict...\n \"\"\"\n join = string.join\n\n declare_return = 'PyObject *return_val = NULL;\\n' \\\n 'int exception_occured = 0;\\n' \\\n 'PyObject *py_local_dict = NULL;\\n'\n arg_string_list = self.arg_specs.variable_as_strings() + ['\"local_dict\"']\n arg_strings = join(arg_string_list,',')\n if arg_strings: arg_strings += ','\n declare_kwlist = 'static char *kwlist[] = {%s NULL};\\n' % arg_strings\n\n py_objects = join(self.arg_specs.py_pointers(),', ')\n if py_objects:\n declare_py_objects = 'PyObject ' + py_objects +';\\n'\n else:\n declare_py_objects = ''\n \n py_vars = join(self.arg_specs.py_variables(),' = ')\n if py_vars:\n init_values = py_vars + ' = NULL;\\n\\n'\n else:\n init_values = '' \n\n #Each variable is in charge of its own cleanup now.\n #cnt = len(arg_list)\n #declare_cleanup = \"blitz::TinyVector clean_up(0);\\n\" % cnt\n\n ref_string = join(self.arg_specs.py_references(),', ')\n if ref_string:\n ref_string += ', &py_local_dict'\n else:\n ref_string = '&py_local_dict'\n \n format = \"O\"* len(self.arg_specs) + \"|O\" + ':' + self.name\n parse_tuple = 'if(!PyArg_ParseTupleAndKeywords(args,' \\\n 'kywds,\"%s\",kwlist,%s))\\n' % (format,ref_string)\n parse_tuple += ' return NULL;\\n'\n\n return declare_return + declare_kwlist + declare_py_objects \\\n + init_values + parse_tuple\n\n def arg_declaration_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.declaration_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_cleanup_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.cleanup_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_local_dict_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.local_dict_code())\n code = string.join(arg_strings,\"\")\n return code\n \n def function_code(self):\n decl_code = indent(self.arg_declaration_code(),4)\n cleanup_code = indent(self.arg_cleanup_code(),4)\n function_code = indent(self.code_block,4)\n local_dict_code = indent(self.arg_local_dict_code(),4)\n\n dict_code = \"if(py_local_dict) \\n\" \\\n \"{ \\n\" \\\n \" Py::Dict local_dict = Py::Dict(py_local_dict); \\n\" + \\\n local_dict_code + \\\n \"} \\n\"\n\n try_code = \"try \\n\" \\\n \"{ \\n\" + \\\n decl_code + \\\n \" /**/ \\n\" + \\\n function_code + \\\n indent(dict_code,4) + \\\n \"\\n} \\n\"\n catch_code = \"catch(...) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n \"} \\n\"\n\n return_code = \" /*cleanup code*/ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n \" {\\n \\n\" \\\n \" Py_INCREF(Py_None); \\n\" \\\n \" return_val = Py_None; \\n\" \\\n \" }\\n \\n\" \\\n \" return return_val; \\n\" \\\n \"} \\n\"\n\n all_code = self.function_declaration_code() + \\\n indent(self.parse_tuple_code(),4) + \\\n indent(try_code,4) + \\\n indent(catch_code,4) + \\\n return_code\n\n return all_code\n\n def python_function_definition_code(self):\n args = (self.name, self.name)\n function_decls = '{\"%s\",(PyCFunction)%s , METH_VARARGS|' \\\n 'METH_KEYWORDS},\\n' % args\n return function_decls\n\n def set_compiler(self,compiler):\n self.compiler = compiler\n for arg in self.arg_specs:\n arg.set_compiler(compiler)\n\n\nclass ext_function(ext_function_from_specs):\n def __init__(self,name,code_block, args, local_dict=None, global_dict=None,\n auto_downcast=1, type_factories=None):\n \n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n if type_factories is None:\n type_factories = default_type_factories\n arg_specs = assign_variable_types(args,local_dict, global_dict,\n auto_downcast, type_factories)\n ext_function_from_specs.__init__(self,name,code_block,arg_specs)\n \n \nimport base_info, common_info, cxx_info, scalar_info\n\nclass ext_module:\n def __init__(self,name,compiler=''):\n standard_info = [common_info.basic_module_info(),\n common_info.file_info(), \n common_info.instance_info(), \n common_info.callable_info(), \n common_info.module_info(), \n cxx_info.cxx_info(),\n scalar_info.scalar_info()]\n self.name = name\n self.functions = []\n self.compiler = compiler\n self.customize = base_info.custom_info()\n self._build_information = base_info.info_list(standard_info)\n \n def add_function(self,func):\n self.functions.append(func)\n def module_code(self):\n code = self.warning_code() + \\\n self.header_code() + \\\n self.support_code() + \\\n self.function_code() + \\\n self.python_function_definition_code() + \\\n self.module_init_code()\n return code\n\n def arg_specs(self):\n all_arg_specs = base_spec.arg_spec_list()\n for func in self.functions:\n all_arg_specs += func.arg_specs\n return all_arg_specs\n\n def build_information(self):\n info = [self.customize] + self._build_information + \\\n self.arg_specs().build_information()\n for func in self.functions:\n info.append(func.customize)\n #redundant, but easiest place to make sure compiler is set\n for i in info:\n i.set_compiler(self.compiler)\n return info\n \n def get_headers(self):\n all_headers = self.build_information().headers()\n\n # blitz/array.h always needs to be first so we hack that here...\n if '\"blitz/array.h\"' in all_headers:\n all_headers.remove('\"blitz/array.h\"')\n all_headers.insert(0,'\"blitz/array.h\"')\n return all_headers\n\n def warning_code(self):\n all_warnings = self.build_information().warnings()\n w=map(lambda x: \"#pragma warning(%s)\\n\" % x,all_warnings)\n return ''.join(w)\n \n def header_code(self):\n h = self.get_headers()\n h= map(lambda x: '#include ' + x + '\\n',h)\n return ''.join(h)\n\n def support_code(self):\n code = self.build_information().support_code()\n return ''.join(code)\n\n def function_code(self):\n all_function_code = \"\"\n for func in self.functions:\n all_function_code += func.function_code()\n return ''.join(all_function_code)\n\n def python_function_definition_code(self):\n all_definition_code = \"\"\n for func in self.functions:\n all_definition_code += func.python_function_definition_code()\n all_definition_code = indent(''.join(all_definition_code),4)\n code = 'static PyMethodDef compiled_methods[] = \\n' \\\n '{\\n' \\\n '%s' \\\n ' {NULL, NULL} /* Sentinel */\\n' \\\n '};\\n'\n return code % (all_definition_code)\n\n def module_init_code(self):\n init_code_list = self.build_information().module_init_code()\n init_code = indent(''.join(init_code_list),4)\n code = 'extern \"C\" void init%s()\\n' \\\n '{\\n' \\\n '%s' \\\n ' (void) Py_InitModule(\"%s\", compiled_methods);\\n' \\\n '}\\n' % (self.name,init_code,self.name)\n return code\n\n def generate_file(self,file_name=\"\",location='.'):\n code = self.module_code()\n if not file_name:\n file_name = self.name + '.cpp'\n name = generate_file_name(file_name,location)\n #return name\n return generate_module(code,name)\n\n def set_compiler(self,compiler):\n #for i in self.arg_specs()\n # i.set_compiler(compiler)\n for i in self.build_information():\n i.set_compiler(compiler) \n for i in self.functions:\n i.set_compiler(compiler)\n self.compiler = compiler \n \n def compile(self,location='.',compiler=None, verbose = 0, **kw):\n \n if compiler is not None:\n self.compiler = compiler\n # hmm. Is there a cleaner way to do this? Seems like\n # choosing the compiler spagettis around a little.\n compiler = build_tools.choose_compiler(self.compiler) \n self.set_compiler(compiler)\n arg_specs = self.arg_specs()\n info = self.build_information()\n _source_files = info.sources()\n # remove duplicates\n source_files = {}\n for i in _source_files:\n source_files[i] = None\n source_files = source_files.keys()\n \n # add internally specified macros, includes, etc. to the key words\n # values of the same names so that distutils will use them.\n kw['define_macros'] = kw.get('define_macros',[]) + info.define_macros()\n kw['include_dirs'] = kw.get('include_dirs',[]) + info.include_dirs()\n kw['libraries'] = kw.get('libraries',[]) + info.libraries()\n kw['library_dirs'] = kw.get('library_dirs',[]) + info.library_dirs()\n \n file = self.generate_file(location=location)\n # This is needed so that files build correctly even when different\n # versions of Python are running around.\n # Imported at beginning of file now to help with test paths.\n # import catalog \n #temp = catalog.default_temp_dir()\n # for speed, build in the machines temp directory\n temp = catalog.intermediate_dir()\n success = build_tools.build_extension(file, temp_dir = temp,\n sources = source_files, \n compiler_name = compiler,\n verbose = verbose, **kw)\n if not success:\n raise SystemError, 'Compilation failed'\n\ndef generate_file_name(module_name,module_location):\n module_file = os.path.join(module_location,module_name)\n return os.path.abspath(module_file)\n\ndef generate_module(module_string, module_file):\n f =open(module_file,'w')\n f.write(module_string)\n f.close()\n return module_file\n\ndef assign_variable_types(variables,local_dict = {}, global_dict = {},\n auto_downcast = 1,\n type_factories = default_type_factories):\n incoming_vars = {}\n incoming_vars.update(global_dict)\n incoming_vars.update(local_dict)\n variable_specs = []\n errors={}\n for var in variables:\n try:\n example_type = incoming_vars[var]\n\n # look through possible type specs to find which one\n # should be used to for example_type\n spec = None\n for factory in type_factories:\n if factory.type_match(example_type):\n spec = factory.type_spec(var,example_type)\n break\n if not spec:\n # should really define our own type.\n raise IndexError\n else:\n variable_specs.append(spec)\n except KeyError:\n errors[var] = (\"The type and dimensionality specifications\" +\n \"for variable '\" + var + \"' are missing.\")\n except IndexError:\n errors[var] = (\"Unable to convert variable '\"+ var +\n \"' to a C++ type.\")\n if errors:\n raise TypeError, format_error_msg(errors)\n\n if auto_downcast:\n variable_specs = downcast(variable_specs)\n return variable_specs\n\ndef downcast(var_specs):\n \"\"\" Cast python scalars down to most common type of\n arrays used.\n\n Right now, focus on complex and float types. Ignore int types.\n Require all arrays to have same type before forcing downcasts.\n\n Note: var_specs are currently altered in place (horrors...!)\n \"\"\"\n numeric_types = []\n\n #grab all the numeric types associated with a variables.\n for var in var_specs:\n if hasattr(var,'numeric_type'):\n numeric_types.append(var.numeric_type)\n\n # if arrays are present, but none of them are double precision,\n # make all numeric types float or complex(float)\n if ( ('f' in numeric_types or 'F' in numeric_types) and\n not ('d' in numeric_types or 'D' in numeric_types) ):\n for var in var_specs:\n if hasattr(var,'numeric_type'):\n # really should do this some other way...\n if var.numeric_type == type(1+1j):\n var.numeric_type = 'F'\n elif var.numeric_type == type(1.):\n var.numeric_type = 'f'\n return var_specs\n\ndef indent(st,spaces):\n indention = ' '*spaces\n indented = indention + string.replace(st,'\\n','\\n'+indention)\n # trim off any trailing spaces\n indented = re.sub(r' +$',r'',indented)\n return indented\n\ndef format_error_msg(errors):\n #minimum effort right now...\n import pprint,cStringIO\n msg = cStringIO.StringIO()\n pprint.pprint(errors,msg)\n return msg.getvalue()\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "import os, sys\nimport string, re\n\nimport build_tools\n\nimport base_spec\nimport scalar_spec\nimport sequence_spec\nimport common_spec\n\ndefault_type_factories = [scalar_spec.int_specification(),\n scalar_spec.float_specification(),\n scalar_spec.complex_specification(),\n sequence_spec.string_specification(),\n sequence_spec.list_specification(),\n sequence_spec.dict_specification(),\n sequence_spec.tuple_specification(),\n common_spec.file_specification(),\n common_spec.callable_specification()]\n #common_spec.instance_specification(), \n #common_spec.module_specification()]\n\ntry: \n from standard_array_spec import array_specification\n default_type_factories.append(array_specification())\nexcept: \n pass \n\ntry: \n # this is currently safe because it doesn't import wxPython.\n import wx_spec\n default_type_factories.append(wx_spec.wx_specification())\nexcept: \n pass \n\nclass ext_function_from_specs:\n def __init__(self,name,code_block,arg_specs):\n self.name = name\n self.arg_specs = base_spec.arg_spec_list(arg_specs)\n self.code_block = code_block\n self.compiler = ''\n self.customize = base_info.custom_info()\n \n def header_code(self):\n pass\n\n def function_declaration_code(self):\n code = 'static PyObject* %s(PyObject*self, PyObject* args,' \\\n ' PyObject* kywds)\\n{\\n'\n return code % self.name\n\n def template_declaration_code(self):\n code = 'template\\n' \\\n 'static PyObject* %s(PyObject*self, PyObject* args,' \\\n ' PyObject* kywds)\\n{\\n'\n return code % self.name\n\n #def cpp_function_declaration_code(self):\n # pass\n #def cpp_function_call_code(self):\n #s pass\n \n def parse_tuple_code(self):\n \"\"\" Create code block for PyArg_ParseTuple. Variable declarations\n for all PyObjects are done also.\n \n This code got a lot uglier when I added local_dict...\n \"\"\"\n join = string.join\n\n declare_return = 'PyObject *return_val = NULL;\\n' \\\n 'int exception_occured = 0;\\n' \\\n 'PyObject *py_local_dict = NULL;\\n'\n arg_string_list = self.arg_specs.variable_as_strings() + ['\"local_dict\"']\n arg_strings = join(arg_string_list,',')\n if arg_strings: arg_strings += ','\n declare_kwlist = 'static char *kwlist[] = {%s NULL};\\n' % arg_strings\n\n py_objects = join(self.arg_specs.py_pointers(),', ')\n if py_objects:\n declare_py_objects = 'PyObject ' + py_objects +';\\n'\n else:\n declare_py_objects = ''\n \n py_vars = join(self.arg_specs.py_variables(),' = ')\n if py_vars:\n init_values = py_vars + ' = NULL;\\n\\n'\n else:\n init_values = '' \n\n #Each variable is in charge of its own cleanup now.\n #cnt = len(arg_list)\n #declare_cleanup = \"blitz::TinyVector clean_up(0);\\n\" % cnt\n\n ref_string = join(self.arg_specs.py_references(),', ')\n if ref_string:\n ref_string += ', &py_local_dict'\n else:\n ref_string = '&py_local_dict'\n \n format = \"O\"* len(self.arg_specs) + \"|O\" + ':' + self.name\n parse_tuple = 'if(!PyArg_ParseTupleAndKeywords(args,' \\\n 'kywds,\"%s\",kwlist,%s))\\n' % (format,ref_string)\n parse_tuple += ' return NULL;\\n'\n\n return declare_return + declare_kwlist + declare_py_objects \\\n + init_values + parse_tuple\n\n def arg_declaration_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.declaration_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_cleanup_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.cleanup_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_local_dict_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.local_dict_code())\n code = string.join(arg_strings,\"\")\n return code\n \n def function_code(self):\n decl_code = indent(self.arg_declaration_code(),4)\n cleanup_code = indent(self.arg_cleanup_code(),4)\n function_code = indent(self.code_block,4)\n local_dict_code = indent(self.arg_local_dict_code(),4)\n\n dict_code = \"if(py_local_dict) \\n\" \\\n \"{ \\n\" \\\n \" Py::Dict local_dict = Py::Dict(py_local_dict); \\n\" + \\\n local_dict_code + \\\n \"} \\n\"\n\n try_code = \"try \\n\" \\\n \"{ \\n\" + \\\n decl_code + \\\n \" /**/ \\n\" + \\\n function_code + \\\n indent(dict_code,4) + \\\n \"\\n} \\n\"\n catch_code = \"catch( Py::Exception& e) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n \"} \\n\"\n\n return_code = \" /*cleanup code*/ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n \" {\\n \\n\" \\\n \" Py_INCREF(Py_None); \\n\" \\\n \" return_val = Py_None; \\n\" \\\n \" }\\n \\n\" \\\n \" return return_val; \\n\" \\\n \"} \\n\"\n\n all_code = self.function_declaration_code() + \\\n indent(self.parse_tuple_code(),4) + \\\n indent(try_code,4) + \\\n indent(catch_code,4) + \\\n return_code\n\n return all_code\n\n def python_function_definition_code(self):\n args = (self.name, self.name)\n function_decls = '{\"%s\",(PyCFunction)%s , METH_VARARGS|' \\\n 'METH_KEYWORDS},\\n' % args\n return function_decls\n\n def set_compiler(self,compiler):\n self.compiler = compiler\n for arg in self.arg_specs:\n arg.set_compiler(compiler)\n\n\nclass ext_function(ext_function_from_specs):\n def __init__(self,name,code_block, args, local_dict=None, global_dict=None,\n auto_downcast=1, type_factories=None):\n \n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n if type_factories is None:\n type_factories = default_type_factories\n arg_specs = assign_variable_types(args,local_dict, global_dict,\n auto_downcast, type_factories)\n ext_function_from_specs.__init__(self,name,code_block,arg_specs)\n \n \nimport base_info, common_info, cxx_info, scalar_info\n\nclass ext_module:\n def __init__(self,name,compiler=''):\n standard_info = [common_info.basic_module_info(),\n common_info.file_info(), \n common_info.instance_info(), \n common_info.callable_info(), \n common_info.module_info(), \n cxx_info.cxx_info(),\n scalar_info.scalar_info()]\n self.name = name\n self.functions = []\n self.compiler = compiler\n self.customize = base_info.custom_info()\n self._build_information = base_info.info_list(standard_info)\n \n def add_function(self,func):\n self.functions.append(func)\n def module_code(self):\n code = self.warning_code() + \\\n self.header_code() + \\\n self.support_code() + \\\n self.function_code() + \\\n self.python_function_definition_code() + \\\n self.module_init_code()\n return code\n\n def arg_specs(self):\n all_arg_specs = base_spec.arg_spec_list()\n for func in self.functions:\n all_arg_specs += func.arg_specs\n return all_arg_specs\n\n def build_information(self):\n info = [self.customize] + self._build_information + \\\n self.arg_specs().build_information()\n for func in self.functions:\n info.append(func.customize)\n #redundant, but easiest place to make sure compiler is set\n for i in info:\n i.set_compiler(self.compiler)\n return info\n \n def get_headers(self):\n all_headers = self.build_information().headers()\n\n # blitz/array.h always needs to be first so we hack that here...\n if '\"blitz/array.h\"' in all_headers:\n all_headers.remove('\"blitz/array.h\"')\n all_headers.insert(0,'\"blitz/array.h\"')\n return all_headers\n\n def warning_code(self):\n all_warnings = self.build_information().warnings()\n w=map(lambda x: \"#pragma warning(%s)\\n\" % x,all_warnings)\n return ''.join(w)\n \n def header_code(self):\n h = self.get_headers()\n h= map(lambda x: '#include ' + x + '\\n',h)\n return ''.join(h)\n\n def support_code(self):\n code = self.build_information().support_code()\n return ''.join(code)\n\n def function_code(self):\n all_function_code = \"\"\n for func in self.functions:\n all_function_code += func.function_code()\n return ''.join(all_function_code)\n\n def python_function_definition_code(self):\n all_definition_code = \"\"\n for func in self.functions:\n all_definition_code += func.python_function_definition_code()\n all_definition_code = indent(''.join(all_definition_code),4)\n code = 'static PyMethodDef compiled_methods[] = \\n' \\\n '{\\n' \\\n '%s' \\\n ' {NULL, NULL} /* Sentinel */\\n' \\\n '};\\n'\n return code % (all_definition_code)\n\n def module_init_code(self):\n init_code_list = self.build_information().module_init_code()\n init_code = indent(''.join(init_code_list),4)\n code = 'extern \"C\" void init%s()\\n' \\\n '{\\n' \\\n '%s' \\\n ' (void) Py_InitModule(\"%s\", compiled_methods);\\n' \\\n '}\\n' % (self.name,init_code,self.name)\n return code\n\n def generate_file(self,file_name=\"\",location='.'):\n code = self.module_code()\n if not file_name:\n file_name = self.name + '.cpp'\n name = generate_file_name(file_name,location)\n #return name\n return generate_module(code,name)\n\n def set_compiler(self,compiler):\n #for i in self.arg_specs()\n # i.set_compiler(compiler)\n for i in self.build_information():\n i.set_compiler(compiler) \n for i in self.functions:\n i.set_compiler(compiler)\n self.compiler = compiler \n \n def compile(self,location='.',compiler=None, verbose = 0, **kw):\n \n if compiler is not None:\n self.compiler = compiler\n # hmm. Is there a cleaner way to do this? Seems like\n # choosing the compiler spagettis around a little.\n compiler = build_tools.choose_compiler(self.compiler) \n self.set_compiler(compiler)\n arg_specs = self.arg_specs()\n info = self.build_information()\n _source_files = info.sources()\n # remove duplicates\n source_files = {}\n for i in _source_files:\n source_files[i] = None\n source_files = source_files.keys()\n \n # add internally specified macros, includes, etc. to the key words\n # values of the same names so that distutils will use them.\n kw['define_macros'] = kw.get('define_macros',[]) + info.define_macros()\n kw['include_dirs'] = kw.get('include_dirs',[]) + info.include_dirs()\n kw['libraries'] = kw.get('libraries',[]) + info.libraries()\n kw['library_dirs'] = kw.get('library_dirs',[]) + info.library_dirs()\n \n file = self.generate_file(location=location)\n # This is needed so that files build correctly even when different\n # versions of Python are running around.\n import catalog \n #temp = catalog.default_temp_dir()\n # for speed, build in the machines temp directory\n temp = catalog.intermediate_dir()\n success = build_tools.build_extension(file, temp_dir = temp,\n sources = source_files, \n compiler_name = compiler,\n verbose = verbose, **kw)\n if not success:\n raise SystemError, 'Compilation failed'\n\ndef generate_file_name(module_name,module_location):\n module_file = os.path.join(module_location,module_name)\n return os.path.abspath(module_file)\n\ndef generate_module(module_string, module_file):\n f =open(module_file,'w')\n f.write(module_string)\n f.close()\n return module_file\n\ndef assign_variable_types(variables,local_dict = {}, global_dict = {},\n auto_downcast = 1,\n type_factories = default_type_factories):\n incoming_vars = {}\n incoming_vars.update(global_dict)\n incoming_vars.update(local_dict)\n variable_specs = []\n errors={}\n for var in variables:\n try:\n example_type = incoming_vars[var]\n\n # look through possible type specs to find which one\n # should be used to for example_type\n spec = None\n for factory in type_factories:\n if factory.type_match(example_type):\n spec = factory.type_spec(var,example_type)\n break\n if not spec:\n # should really define our own type.\n raise IndexError\n else:\n variable_specs.append(spec)\n except KeyError:\n errors[var] = (\"The type and dimensionality specifications\" +\n \"for variable '\" + var + \"' are missing.\")\n except IndexError:\n errors[var] = (\"Unable to convert variable '\"+ var +\n \"' to a C++ type.\")\n if errors:\n raise TypeError, format_error_msg(errors)\n\n if auto_downcast:\n variable_specs = downcast(variable_specs)\n return variable_specs\n\ndef downcast(var_specs):\n \"\"\" Cast python scalars down to most common type of\n arrays used.\n\n Right now, focus on complex and float types. Ignore int types.\n Require all arrays to have same type before forcing downcasts.\n\n Note: var_specs are currently altered in place (horrors...!)\n \"\"\"\n numeric_types = []\n\n #grab all the numeric types associated with a variables.\n for var in var_specs:\n if hasattr(var,'numeric_type'):\n numeric_types.append(var.numeric_type)\n\n # if arrays are present, but none of them are double precision,\n # make all numeric types float or complex(float)\n if ( ('f' in numeric_types or 'F' in numeric_types) and\n not ('d' in numeric_types or 'D' in numeric_types) ):\n for var in var_specs:\n if hasattr(var,'numeric_type'):\n # really should do this some other way...\n if var.numeric_type == type(1+1j):\n var.numeric_type = 'F'\n elif var.numeric_type == type(1.):\n var.numeric_type = 'f'\n return var_specs\n\ndef indent(st,spaces):\n indention = ' '*spaces\n indented = indention + string.replace(st,'\\n','\\n'+indention)\n # trim off any trailing spaces\n indented = re.sub(r' +$',r'',indented)\n return indented\n\ndef format_error_msg(errors):\n #minimum effort right now...\n import pprint,cStringIO\n msg = cStringIO.StringIO()\n pprint.pprint(errors,msg)\n return msg.getvalue()\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "methods": [ { "name": "__init__", "long_name": "__init__( self , name , code_block , arg_specs )", "filename": "ext_tools.py", "nloc": 6, "complexity": 1, "token_count": 45, "parameters": [ "self", "name", "code_block", "arg_specs" ], "start_line": 38, "end_line": 43, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "header_code", "long_name": "header_code( self )", "filename": "ext_tools.py", "nloc": 2, "complexity": 1, "token_count": 6, "parameters": [ "self" ], "start_line": 45, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "function_declaration_code", "long_name": "function_declaration_code( self )", "filename": "ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 16, "parameters": [ "self" ], "start_line": 48, "end_line": 51, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "template_declaration_code", "long_name": "template_declaration_code( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 53, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "parse_tuple_code", "long_name": "parse_tuple_code( self )", "filename": "ext_tools.py", "nloc": 30, "complexity": 5, "token_count": 174, "parameters": [ "self" ], "start_line": 64, "end_line": 108, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 45, "top_nesting_level": 1 }, { "name": "arg_declaration_code", "long_name": "arg_declaration_code( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 110, "end_line": 115, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_cleanup_code", "long_name": "arg_cleanup_code( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 117, "end_line": 122, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_local_dict_code", "long_name": "arg_local_dict_code( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 124, "end_line": 129, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "ext_tools.py", "nloc": 37, "complexity": 1, "token_count": 162, "parameters": [ "self" ], "start_line": 131, "end_line": 172, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 174, "end_line": 178, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "set_compiler", "long_name": "set_compiler( self , compiler )", "filename": "ext_tools.py", "nloc": 4, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 180, "end_line": 183, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , code_block , args , local_dict = None , global_dict = None , auto_downcast = 1 , type_factories = None )", "filename": "ext_tools.py", "nloc": 12, "complexity": 4, "token_count": 90, "parameters": [ "self", "name", "code_block", "args", "local_dict", "global_dict", "auto_downcast", "type_factories" ], "start_line": 187, "end_line": 199, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , compiler = '' )", "filename": "ext_tools.py", "nloc": 13, "complexity": 1, "token_count": 91, "parameters": [ "self", "name", "compiler" ], "start_line": 205, "end_line": 217, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "add_function", "long_name": "add_function( self , func )", "filename": "ext_tools.py", "nloc": 2, "complexity": 1, "token_count": 15, "parameters": [ "self", "func" ], "start_line": 219, "end_line": 220, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "module_code", "long_name": "module_code( self )", "filename": "ext_tools.py", "nloc": 8, "complexity": 1, "token_count": 49, "parameters": [ "self" ], "start_line": 221, "end_line": 228, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "arg_specs", "long_name": "arg_specs( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 2, "token_count": 26, "parameters": [ "self" ], "start_line": 230, "end_line": 234, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "build_information", "long_name": "build_information( self )", "filename": "ext_tools.py", "nloc": 8, "complexity": 3, "token_count": 57, "parameters": [ "self" ], "start_line": 236, "end_line": 244, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "get_headers", "long_name": "get_headers( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 37, "parameters": [ "self" ], "start_line": 246, "end_line": 253, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "warning_code", "long_name": "warning_code( self )", "filename": "ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 36, "parameters": [ "self" ], "start_line": 255, "end_line": 258, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "header_code", "long_name": "header_code( self )", "filename": "ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 34, "parameters": [ "self" ], "start_line": 260, "end_line": 263, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "support_code", "long_name": "support_code( self )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 265, "end_line": 267, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 2, "token_count": 29, "parameters": [ "self" ], "start_line": 269, "end_line": 273, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "ext_tools.py", "nloc": 11, "complexity": 2, "token_count": 52, "parameters": [ "self" ], "start_line": 275, "end_line": 285, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "module_init_code", "long_name": "module_init_code( self )", "filename": "ext_tools.py", "nloc": 9, "complexity": 1, "token_count": 54, "parameters": [ "self" ], "start_line": 287, "end_line": 295, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "generate_file", "long_name": "generate_file( self , file_name = \"\" , location = '.' )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 46, "parameters": [ "self", "file_name", "location" ], "start_line": 297, "end_line": 303, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "set_compiler", "long_name": "set_compiler( self , compiler )", "filename": "ext_tools.py", "nloc": 6, "complexity": 3, "token_count": 40, "parameters": [ "self", "compiler" ], "start_line": 305, "end_line": 312, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "compile", "long_name": "compile( self , location = '.' , compiler = None , verbose = 0 , ** kw )", "filename": "ext_tools.py", "nloc": 24, "complexity": 4, "token_count": 222, "parameters": [ "self", "location", "compiler", "verbose", "kw" ], "start_line": 314, "end_line": 351, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 38, "top_nesting_level": 1 }, { "name": "generate_file_name", "long_name": "generate_file_name( module_name , module_location )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 28, "parameters": [ "module_name", "module_location" ], "start_line": 353, "end_line": 355, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "generate_module", "long_name": "generate_module( module_string , module_file )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 28, "parameters": [ "module_string", "module_file" ], "start_line": 357, "end_line": 361, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 }, { "name": "assign_variable_types", "long_name": "assign_variable_types( variables , local_dict = { } , global_dict = { } , auto_downcast = 1 , type_factories = default_type_factories )", "filename": "ext_tools.py", "nloc": 31, "complexity": 9, "token_count": 154, "parameters": [ "variables", "local_dict", "global_dict", "auto_downcast", "type_factories" ], "start_line": 363, "end_line": 398, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "downcast", "long_name": "downcast( var_specs )", "filename": "ext_tools.py", "nloc": 14, "complexity": 11, "token_count": 103, "parameters": [ "var_specs" ], "start_line": 400, "end_line": 427, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 28, "top_nesting_level": 0 }, { "name": "indent", "long_name": "indent( st , spaces )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 44, "parameters": [ "st", "spaces" ], "start_line": 429, "end_line": 434, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "format_error_msg", "long_name": "format_error_msg( errors )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 30, "parameters": [ "errors" ], "start_line": 436, "end_line": 441, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 443, "end_line": 445, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 447, "end_line": 449, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "__init__", "long_name": "__init__( self , name , code_block , arg_specs )", "filename": "ext_tools.py", "nloc": 6, "complexity": 1, "token_count": 45, "parameters": [ "self", "name", "code_block", "arg_specs" ], "start_line": 37, "end_line": 42, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "header_code", "long_name": "header_code( self )", "filename": "ext_tools.py", "nloc": 2, "complexity": 1, "token_count": 6, "parameters": [ "self" ], "start_line": 44, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "function_declaration_code", "long_name": "function_declaration_code( self )", "filename": "ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 16, "parameters": [ "self" ], "start_line": 47, "end_line": 50, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "template_declaration_code", "long_name": "template_declaration_code( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 52, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "parse_tuple_code", "long_name": "parse_tuple_code( self )", "filename": "ext_tools.py", "nloc": 30, "complexity": 5, "token_count": 174, "parameters": [ "self" ], "start_line": 63, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 45, "top_nesting_level": 1 }, { "name": "arg_declaration_code", "long_name": "arg_declaration_code( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 109, "end_line": 114, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_cleanup_code", "long_name": "arg_cleanup_code( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 116, "end_line": 121, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_local_dict_code", "long_name": "arg_local_dict_code( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 123, "end_line": 128, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "ext_tools.py", "nloc": 37, "complexity": 1, "token_count": 162, "parameters": [ "self" ], "start_line": 130, "end_line": 171, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 173, "end_line": 177, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "set_compiler", "long_name": "set_compiler( self , compiler )", "filename": "ext_tools.py", "nloc": 4, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 179, "end_line": 182, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , code_block , args , local_dict = None , global_dict = None , auto_downcast = 1 , type_factories = None )", "filename": "ext_tools.py", "nloc": 12, "complexity": 4, "token_count": 90, "parameters": [ "self", "name", "code_block", "args", "local_dict", "global_dict", "auto_downcast", "type_factories" ], "start_line": 186, "end_line": 198, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , compiler = '' )", "filename": "ext_tools.py", "nloc": 13, "complexity": 1, "token_count": 91, "parameters": [ "self", "name", "compiler" ], "start_line": 204, "end_line": 216, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "add_function", "long_name": "add_function( self , func )", "filename": "ext_tools.py", "nloc": 2, "complexity": 1, "token_count": 15, "parameters": [ "self", "func" ], "start_line": 218, "end_line": 219, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "module_code", "long_name": "module_code( self )", "filename": "ext_tools.py", "nloc": 8, "complexity": 1, "token_count": 49, "parameters": [ "self" ], "start_line": 220, "end_line": 227, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "arg_specs", "long_name": "arg_specs( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 2, "token_count": 26, "parameters": [ "self" ], "start_line": 229, "end_line": 233, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "build_information", "long_name": "build_information( self )", "filename": "ext_tools.py", "nloc": 8, "complexity": 3, "token_count": 57, "parameters": [ "self" ], "start_line": 235, "end_line": 243, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "get_headers", "long_name": "get_headers( self )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 37, "parameters": [ "self" ], "start_line": 245, "end_line": 252, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "warning_code", "long_name": "warning_code( self )", "filename": "ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 36, "parameters": [ "self" ], "start_line": 254, "end_line": 257, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "header_code", "long_name": "header_code( self )", "filename": "ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 34, "parameters": [ "self" ], "start_line": 259, "end_line": 262, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "support_code", "long_name": "support_code( self )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 264, "end_line": 266, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "ext_tools.py", "nloc": 5, "complexity": 2, "token_count": 29, "parameters": [ "self" ], "start_line": 268, "end_line": 272, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "ext_tools.py", "nloc": 11, "complexity": 2, "token_count": 52, "parameters": [ "self" ], "start_line": 274, "end_line": 284, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "module_init_code", "long_name": "module_init_code( self )", "filename": "ext_tools.py", "nloc": 9, "complexity": 1, "token_count": 54, "parameters": [ "self" ], "start_line": 286, "end_line": 294, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "generate_file", "long_name": "generate_file( self , file_name = \"\" , location = '.' )", "filename": "ext_tools.py", "nloc": 6, "complexity": 2, "token_count": 46, "parameters": [ "self", "file_name", "location" ], "start_line": 296, "end_line": 302, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "set_compiler", "long_name": "set_compiler( self , compiler )", "filename": "ext_tools.py", "nloc": 6, "complexity": 3, "token_count": 40, "parameters": [ "self", "compiler" ], "start_line": 304, "end_line": 311, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "compile", "long_name": "compile( self , location = '.' , compiler = None , verbose = 0 , ** kw )", "filename": "ext_tools.py", "nloc": 25, "complexity": 4, "token_count": 224, "parameters": [ "self", "location", "compiler", "verbose", "kw" ], "start_line": 313, "end_line": 349, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 37, "top_nesting_level": 1 }, { "name": "generate_file_name", "long_name": "generate_file_name( module_name , module_location )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 28, "parameters": [ "module_name", "module_location" ], "start_line": 351, "end_line": 353, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "generate_module", "long_name": "generate_module( module_string , module_file )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 28, "parameters": [ "module_string", "module_file" ], "start_line": 355, "end_line": 359, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 }, { "name": "assign_variable_types", "long_name": "assign_variable_types( variables , local_dict = { } , global_dict = { } , auto_downcast = 1 , type_factories = default_type_factories )", "filename": "ext_tools.py", "nloc": 31, "complexity": 9, "token_count": 154, "parameters": [ "variables", "local_dict", "global_dict", "auto_downcast", "type_factories" ], "start_line": 361, "end_line": 396, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "downcast", "long_name": "downcast( var_specs )", "filename": "ext_tools.py", "nloc": 14, "complexity": 11, "token_count": 103, "parameters": [ "var_specs" ], "start_line": 398, "end_line": 425, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 28, "top_nesting_level": 0 }, { "name": "indent", "long_name": "indent( st , spaces )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 44, "parameters": [ "st", "spaces" ], "start_line": 427, "end_line": 432, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "format_error_msg", "long_name": "format_error_msg( errors )", "filename": "ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 30, "parameters": [ "errors" ], "start_line": 434, "end_line": 439, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 441, "end_line": 443, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "ext_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 445, "end_line": 447, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "function_code", "long_name": "function_code( self )", "filename": "ext_tools.py", "nloc": 37, "complexity": 1, "token_count": 162, "parameters": [ "self" ], "start_line": 131, "end_line": 172, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "compile", "long_name": "compile( self , location = '.' , compiler = None , verbose = 0 , ** kw )", "filename": "ext_tools.py", "nloc": 24, "complexity": 4, "token_count": 222, "parameters": [ "self", "location", "compiler", "verbose", "kw" ], "start_line": 314, "end_line": 351, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 38, "top_nesting_level": 1 } ], "nloc": 337, "complexity": 76, "token_count": 2068, "diff_parsed": { "added": [ "import catalog", " catch_code = \"catch(...) \\n\" \\", " # Imported at beginning of file now to help with test paths.", " # import catalog" ], "deleted": [ " catch_code = \"catch( Py::Exception& e) \\n\" \\", " import catalog" ] } }, { "old_path": "weave/inline_info.py", "new_path": "weave/inline_info.py", "filename": "inline_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -4,7 +4,7 @@\n {\n char msg[500];\n sprintf(msg,\"variable '%s' not found in local or global scope.\",var_name);\n- throw Py::NameError(msg);\n+ throw_error(PyExc_NameError,msg);\n }\n PyObject* get_variable(char* name,PyObject* locals, PyObject* globals)\n {\n", "added_lines": 1, "deleted_lines": 1, "source_code": "get_variable_support_code = \\\n\"\"\"\nvoid handle_variable_not_found(char* var_name)\n{\n char msg[500];\n sprintf(msg,\"variable '%s' not found in local or global scope.\",var_name);\n throw_error(PyExc_NameError,msg);\n}\nPyObject* get_variable(char* name,PyObject* locals, PyObject* globals)\n{\n // no checking done for error -- locals and globals should\n // already be validated as dictionaries. If var is NULL, the\n // function calling this should handle it.\n PyObject* var = NULL;\n var = PyDict_GetItemString(locals,name);\n if (!var)\n {\n var = PyDict_GetItemString(globals,name);\n }\n if (!var)\n handle_variable_not_found(name);\n return var;\n}\n\"\"\"\n\npy_to_raw_dict_support_code = \\\n\"\"\"\nPyObject* py_to_raw_dict(PyObject* py_obj, char* name)\n{\n // simply check that the value is a valid dictionary pointer.\n if(!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj, \"dictionary\", name);\n return py_obj;\n}\n\"\"\"\n\nimport base_info\nclass inline_info(base_info.base_info):\n _support_code = [get_variable_support_code, py_to_raw_dict_support_code]\n", "source_code_before": "get_variable_support_code = \\\n\"\"\"\nvoid handle_variable_not_found(char* var_name)\n{\n char msg[500];\n sprintf(msg,\"variable '%s' not found in local or global scope.\",var_name);\n throw Py::NameError(msg);\n}\nPyObject* get_variable(char* name,PyObject* locals, PyObject* globals)\n{\n // no checking done for error -- locals and globals should\n // already be validated as dictionaries. If var is NULL, the\n // function calling this should handle it.\n PyObject* var = NULL;\n var = PyDict_GetItemString(locals,name);\n if (!var)\n {\n var = PyDict_GetItemString(globals,name);\n }\n if (!var)\n handle_variable_not_found(name);\n return var;\n}\n\"\"\"\n\npy_to_raw_dict_support_code = \\\n\"\"\"\nPyObject* py_to_raw_dict(PyObject* py_obj, char* name)\n{\n // simply check that the value is a valid dictionary pointer.\n if(!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj, \"dictionary\", name);\n return py_obj;\n}\n\"\"\"\n\nimport base_info\nclass inline_info(base_info.base_info):\n _support_code = [get_variable_support_code, py_to_raw_dict_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 37, "complexity": 0, "token_count": 25, "diff_parsed": { "added": [ " throw_error(PyExc_NameError,msg);" ], "deleted": [ " throw Py::NameError(msg);" ] } }, { "old_path": "weave/inline_tools.py", "new_path": "weave/inline_tools.py", "filename": "inline_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -96,11 +96,11 @@ def function_code(self):\n ' /*I would like to fill in changed ' \\\n 'locals and globals here...*/ \\n' \\\n '\\n} \\n'\n- catch_code = \"catch( Py::Exception& e) \\n\" \\\n+ catch_code = \"catch(...) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n- \"} \\n\"\n+ \"} \\n\" \n return_code = \" /* cleanup code */ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n@@ -296,9 +296,14 @@ def inline(code,arg_names=[],local_dict = None, global_dict = None,\n try:\n results = apply(function_cache[code],(local_dict,global_dict))\n return results\n- except:\n+ except TypeError, msg: # should specify argument types here.\n+ msg = str(msg)\n+ if msg[:16] == \"Conversion Error\":\n+ pass\n+ else:\n+ raise TypeError, msg\n+ except KeyError:\n pass\n-\n # 2. try function catalog\n try:\n results = attempt_function_call(code,local_dict,global_dict)\n", "added_lines": 9, "deleted_lines": 4, "source_code": "# should re-write compiled functions to take a local and global dict\n# as input.\nimport sys,os\nimport ext_tools\nimport string\nimport catalog\nimport inline_info, cxx_info\n\n# not an easy way for the user_path_list to come in here.\n# the PYTHONCOMPILED environment variable offers the most hope.\n\nfunction_catalog = catalog.catalog()\n\n\nclass inline_ext_function(ext_tools.ext_function):\n # Some specialization is needed for inline extension functions\n def function_declaration_code(self):\n code = 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def template_declaration_code(self):\n code = 'template\\n' \\\n 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def parse_tuple_code(self):\n \"\"\" Create code block for PyArg_ParseTuple. Variable declarations\n for all PyObjects are done also.\n\n This code got a lot uglier when I added local_dict...\n \"\"\"\n declare_return = 'PyObject *return_val = NULL;\\n' \\\n 'int exception_occured = 0;\\n' \\\n 'PyObject *py__locals = NULL;\\n' \\\n 'PyObject *py__globals = NULL;\\n'\n\n py_objects = ', '.join(self.arg_specs.py_pointers())\n if py_objects:\n declare_py_objects = 'PyObject ' + py_objects +';\\n'\n else:\n declare_py_objects = ''\n\n py_vars = ' = '.join(self.arg_specs.py_variables())\n if py_vars:\n init_values = py_vars + ' = NULL;\\n\\n'\n else:\n init_values = ''\n\n parse_tuple = 'if(!PyArg_ParseTuple(args,\"OO:compiled_func\",'\\\n '&py__locals,'\\\n '&py__globals))\\n'\\\n ' return NULL;\\n'\n\n return declare_return + declare_py_objects + \\\n init_values + parse_tuple\n\n def arg_declaration_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.declaration_code(inline=1))\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_cleanup_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.cleanup_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_local_dict_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.local_dict_code())\n code = string.join(arg_strings,\"\")\n return code\n\n\n def function_code(self):\n from ext_tools import indent\n decl_code = indent(self.arg_declaration_code(),4)\n cleanup_code = indent(self.arg_cleanup_code(),4)\n function_code = indent(self.code_block,4)\n #local_dict_code = indent(self.arg_local_dict_code(),4)\n\n try_code = 'try \\n' \\\n '{ \\n' \\\n ' PyObject* raw_locals = py_to_raw_dict(' \\\n 'py__locals,\"_locals\");\\n' \\\n ' PyObject* raw_globals = py_to_raw_dict(' \\\n 'py__globals,\"_globals\");\\n' + \\\n ' /* argument conversion code */ \\n' + \\\n decl_code + \\\n ' /* inline code */ \\n' + \\\n function_code + \\\n ' /*I would like to fill in changed ' \\\n 'locals and globals here...*/ \\n' \\\n '\\n} \\n'\n catch_code = \"catch(...) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n \"} \\n\" \n return_code = \" /* cleanup code */ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n \" {\\n \\n\" \\\n \" Py_INCREF(Py_None); \\n\" \\\n \" return_val = Py_None; \\n\" \\\n \" }\\n \\n\" \\\n \" return return_val; \\n\" \\\n \"} \\n\"\n\n all_code = self.function_declaration_code() + \\\n indent(self.parse_tuple_code(),4) + \\\n indent(try_code,4) + \\\n indent(catch_code,4) + \\\n return_code\n\n return all_code\n\n def python_function_definition_code(self):\n args = (self.name, self.name)\n function_decls = '{\"%s\",(PyCFunction)%s , METH_VARARGS},\\n' % args\n return function_decls\n\nclass inline_ext_module(ext_tools.ext_module):\n def __init__(self,name,compiler=''):\n ext_tools.ext_module.__init__(self,name,compiler)\n self._build_information.append(inline_info.inline_info())\n\nfunction_cache = {}\ndef inline(code,arg_names=[],local_dict = None, global_dict = None,\n force = 0,\n compiler='',\n verbose = 0,\n support_code = None,\n customize=None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n \"\"\" Inline C/C++ code within Python scripts.\n\n inline() compiles and executes C/C++ code on the fly. Variables\n in the local and global Python scope are also available in the\n C/C++ code. Values are passed to the C/C++ code by assignment\n much like variables passed are passed into a standard Python\n function. Values are returned from the C/C++ code through a\n special argument called return_val. Also, the contents of\n mutable objects can be changed within the C/C++ code and the\n changes remain after the C code exits and returns to Python.\n\n inline has quite a few options as listed below. Also, the keyword\n arguments for distutils extension modules are accepted to\n specify extra information needed for compiling.\n\n code -- string. A string of valid C++ code. It should not specify a\n return statement. Instead it should assign results that\n need to be returned to Python in the return_val.\n arg_names -- optional. list of strings. A list of Python variable names \n that should be transferred from Python into the C/C++ \n code. It defaults to an empty string.\n local_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the local scope for the\n C/C++ code. If local_dict is not specified the local\n dictionary of the calling function is used.\n global_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the global scope for\n the C/C++ code. If global_dict is not specified the\n global dictionary of the calling function is used.\n force -- optional. 0 or 1. default 0. If 1, the C++ code is\n compiled every time inline is called. This is really\n only useful for debugging, and probably only useful if\n your editing support_code a lot.\n compiler -- optional. string. The name of compiler to use when\n compiling. On windows, it understands 'msvc' and 'gcc'\n as well as all the compiler names understood by\n distutils. On Unix, it'll only understand the values\n understoof by distutils. ( I should add 'gcc' though\n to this).\n\n On windows, the compiler defaults to the Microsoft C++\n compiler. If this isn't available, it looks for mingw32\n (the gcc compiler).\n\n On Unix, it'll probably use the same compiler that was\n used when compiling Python. Cygwin's behavior should be\n similar.\n verbose -- optional. 0,1, or 2. defualt 0. Speficies how much\n much information is printed during the compile phase\n of inlining code. 0 is silent (except on windows with\n msvc where it still prints some garbage). 1 informs\n you when compiling starts, finishes, and how long it\n took. 2 prints out the command lines for the compilation\n process and can be useful if your having problems\n getting code to work. Its handy for finding the name\n of the .cpp file if you need to examine it. verbose has\n no affect if the compilation isn't necessary.\n support_code -- optional. string. A string of valid C++ code declaring\n extra code that might be needed by your compiled\n function. This could be declarations of functions,\n classes, or structures.\n customize -- optional. base_info.custom_info object. An alternative\n way to specifiy support_code, headers, etc. needed by\n the function see the compiler.base_info module for more\n details. (not sure this'll be used much).\n type_factories -- optional. list of type specification factories. These\n guys are what convert Python data types to C/C++ data\n types. If you'd like to use a different set of type\n conversions than the default, specify them here. Look\n in the type conversions section of the main\n documentation for examples.\n auto_downcast -- optional. 0 or 1. default 1. This only affects\n functions that have Numeric arrays as input variables.\n Setting this to 1 will cause all floating point values\n to be cast as float instead of double if all the\n Numeric arrays are of type float. If even one of the\n arrays has type double or double complex, all\n variables maintain there standard types.\n\n Distutils keywords. These are cut and pasted from Greg Ward's\n distutils.extension.Extension class for convenience:\n\n sources : [string]\n list of source filenames, relative to the distribution root\n (where the setup script lives), in Unix form (slash-separated)\n for portability. Source files may be C, C++, SWIG (.i),\n platform-specific resource files, or whatever else is recognized\n by the \"build_ext\" command as source for a Python extension.\n Note: The module_path file is always appended to the front of this\n list\n include_dirs : [string]\n list of directories to search for C/C++ header files (in Unix\n form for portability)\n define_macros : [(name : string, value : string|None)]\n list of macros to define; each macro is defined using a 2-tuple,\n where 'value' is either the string to define it to or None to\n define it without a particular value (equivalent of \"#define\n FOO\" in source or -DFOO on Unix C compiler command line)\n undef_macros : [string]\n list of macros to undefine explicitly\n library_dirs : [string]\n list of directories to search for C/C++ libraries at link time\n libraries : [string]\n list of library names (not filenames or paths) to link against\n runtime_library_dirs : [string]\n list of directories to search for C/C++ libraries at run time\n (for shared extensions, this is when the extension is loaded)\n extra_objects : [string]\n list of extra files to link with (eg. object files not implied\n by 'sources', static library that must be explicitly specified,\n binary resource files, etc.)\n extra_compile_args : [string]\n any extra platform- and compiler-specific information to use\n when compiling the source files in 'sources'. For platforms and\n compilers where \"command line\" makes sense, this is typically a\n list of command-line arguments, but for other platforms it could\n be anything.\n extra_link_args : [string]\n any extra platform- and compiler-specific information to use\n when linking object files together to create the extension (or\n to create a new static Python interpreter). Similar\n interpretation as for 'extra_compile_args'.\n export_symbols : [string]\n list of symbols to be exported from a shared extension. Not\n used on all platforms, and not generally necessary for Python\n extensions, which typically export exactly one symbol: \"init\" +\n extension_name.\n \"\"\"\n # this grabs the local variables from the *previous* call\n # frame -- that is the locals from the function that called\n # inline.\n global function_catalog\n\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n if force:\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n else:\n # 1. try local cache\n try:\n results = apply(function_cache[code],(local_dict,global_dict))\n return results\n except TypeError, msg: # should specify argument types here.\n msg = str(msg)\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n except KeyError:\n pass\n # 2. try function catalog\n try:\n results = attempt_function_call(code,local_dict,global_dict)\n # 3. build the function\n except ValueError:\n # compile the library\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n return results\n\ndef attempt_function_call(code,local_dict,global_dict):\n # we try 3 levels here -- a local cache first, then the\n # catalog cache, and then persistent catalog.\n #\n global function_cache\n # 2. try catalog cache.\n function_list = function_catalog.get_functions_fast(code)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except TypeError, msg: # should specify argument types here.\n # This should really have its own error type, instead of\n # checking the beginning of the message, but I don't know\n # how to define that yet.\n msg = str(msg)\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n \n # 3. try persistent catalog\n module_dir = global_dict.get('__file__',None)\n function_list = function_catalog.get_functions(code,module_dir)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except: # should specify argument types here.\n pass\n # if we get here, the function wasn't found\n raise ValueError, 'function with correct signature not found'\n\ndef inline_function_code(code,arg_names,local_dict=None,\n global_dict=None,auto_downcast = 1,\n type_factories=None,compiler=''):\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n import build_tools\n compiler = build_tools.choose_compiler(compiler)\n ext_func.set_compiler(compiler)\n return ext_func.function_code()\n\ndef compile_function(code,arg_names,local_dict,global_dict,\n module_dir,\n compiler='',\n verbose = 0,\n support_code = None,\n customize = None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n # figure out where to store and what to name the extension module\n # that will contain the function.\n #storage_dir = catalog.intermediate_dir()\n module_path = function_catalog.unique_module_name(code,module_dir)\n storage_dir, module_name = os.path.split(module_path)\n mod = inline_ext_module(module_name,compiler)\n\n # create the function. This relies on the auto_downcast and\n # type factories setting\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n mod.add_function(ext_func)\n\n # if customize (a custom_info object), then set the module customization.\n if customize:\n mod.customize = customize\n\n # add the extra \"support code\" needed by the function to the module.\n if support_code:\n mod.customize.add_support_code(support_code)\n \n # compile code in correct location, with the given compiler and verbosity\n # setting. All input keywords are passed through to distutils\n mod.compile(location=storage_dir,compiler=compiler,\n verbose=verbose, **kw)\n\n # import the module and return the function. Make sure\n # the directory where it lives is in the python path.\n try:\n sys.path.insert(0,storage_dir)\n exec 'import ' + module_name\n func = eval(module_name+'.compiled_func')\n finally:\n del sys.path[0]\n return func\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\nif __name__ == \"__main__\":\n test_function()\n", "source_code_before": "# should re-write compiled functions to take a local and global dict\n# as input.\nimport sys,os\nimport ext_tools\nimport string\nimport catalog\nimport inline_info, cxx_info\n\n# not an easy way for the user_path_list to come in here.\n# the PYTHONCOMPILED environment variable offers the most hope.\n\nfunction_catalog = catalog.catalog()\n\n\nclass inline_ext_function(ext_tools.ext_function):\n # Some specialization is needed for inline extension functions\n def function_declaration_code(self):\n code = 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def template_declaration_code(self):\n code = 'template\\n' \\\n 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def parse_tuple_code(self):\n \"\"\" Create code block for PyArg_ParseTuple. Variable declarations\n for all PyObjects are done also.\n\n This code got a lot uglier when I added local_dict...\n \"\"\"\n declare_return = 'PyObject *return_val = NULL;\\n' \\\n 'int exception_occured = 0;\\n' \\\n 'PyObject *py__locals = NULL;\\n' \\\n 'PyObject *py__globals = NULL;\\n'\n\n py_objects = ', '.join(self.arg_specs.py_pointers())\n if py_objects:\n declare_py_objects = 'PyObject ' + py_objects +';\\n'\n else:\n declare_py_objects = ''\n\n py_vars = ' = '.join(self.arg_specs.py_variables())\n if py_vars:\n init_values = py_vars + ' = NULL;\\n\\n'\n else:\n init_values = ''\n\n parse_tuple = 'if(!PyArg_ParseTuple(args,\"OO:compiled_func\",'\\\n '&py__locals,'\\\n '&py__globals))\\n'\\\n ' return NULL;\\n'\n\n return declare_return + declare_py_objects + \\\n init_values + parse_tuple\n\n def arg_declaration_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.declaration_code(inline=1))\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_cleanup_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.cleanup_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_local_dict_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.local_dict_code())\n code = string.join(arg_strings,\"\")\n return code\n\n\n def function_code(self):\n from ext_tools import indent\n decl_code = indent(self.arg_declaration_code(),4)\n cleanup_code = indent(self.arg_cleanup_code(),4)\n function_code = indent(self.code_block,4)\n #local_dict_code = indent(self.arg_local_dict_code(),4)\n\n try_code = 'try \\n' \\\n '{ \\n' \\\n ' PyObject* raw_locals = py_to_raw_dict(' \\\n 'py__locals,\"_locals\");\\n' \\\n ' PyObject* raw_globals = py_to_raw_dict(' \\\n 'py__globals,\"_globals\");\\n' + \\\n ' /* argument conversion code */ \\n' + \\\n decl_code + \\\n ' /* inline code */ \\n' + \\\n function_code + \\\n ' /*I would like to fill in changed ' \\\n 'locals and globals here...*/ \\n' \\\n '\\n} \\n'\n catch_code = \"catch( Py::Exception& e) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n \"} \\n\"\n return_code = \" /* cleanup code */ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n \" {\\n \\n\" \\\n \" Py_INCREF(Py_None); \\n\" \\\n \" return_val = Py_None; \\n\" \\\n \" }\\n \\n\" \\\n \" return return_val; \\n\" \\\n \"} \\n\"\n\n all_code = self.function_declaration_code() + \\\n indent(self.parse_tuple_code(),4) + \\\n indent(try_code,4) + \\\n indent(catch_code,4) + \\\n return_code\n\n return all_code\n\n def python_function_definition_code(self):\n args = (self.name, self.name)\n function_decls = '{\"%s\",(PyCFunction)%s , METH_VARARGS},\\n' % args\n return function_decls\n\nclass inline_ext_module(ext_tools.ext_module):\n def __init__(self,name,compiler=''):\n ext_tools.ext_module.__init__(self,name,compiler)\n self._build_information.append(inline_info.inline_info())\n\nfunction_cache = {}\ndef inline(code,arg_names=[],local_dict = None, global_dict = None,\n force = 0,\n compiler='',\n verbose = 0,\n support_code = None,\n customize=None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n \"\"\" Inline C/C++ code within Python scripts.\n\n inline() compiles and executes C/C++ code on the fly. Variables\n in the local and global Python scope are also available in the\n C/C++ code. Values are passed to the C/C++ code by assignment\n much like variables passed are passed into a standard Python\n function. Values are returned from the C/C++ code through a\n special argument called return_val. Also, the contents of\n mutable objects can be changed within the C/C++ code and the\n changes remain after the C code exits and returns to Python.\n\n inline has quite a few options as listed below. Also, the keyword\n arguments for distutils extension modules are accepted to\n specify extra information needed for compiling.\n\n code -- string. A string of valid C++ code. It should not specify a\n return statement. Instead it should assign results that\n need to be returned to Python in the return_val.\n arg_names -- optional. list of strings. A list of Python variable names \n that should be transferred from Python into the C/C++ \n code. It defaults to an empty string.\n local_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the local scope for the\n C/C++ code. If local_dict is not specified the local\n dictionary of the calling function is used.\n global_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the global scope for\n the C/C++ code. If global_dict is not specified the\n global dictionary of the calling function is used.\n force -- optional. 0 or 1. default 0. If 1, the C++ code is\n compiled every time inline is called. This is really\n only useful for debugging, and probably only useful if\n your editing support_code a lot.\n compiler -- optional. string. The name of compiler to use when\n compiling. On windows, it understands 'msvc' and 'gcc'\n as well as all the compiler names understood by\n distutils. On Unix, it'll only understand the values\n understoof by distutils. ( I should add 'gcc' though\n to this).\n\n On windows, the compiler defaults to the Microsoft C++\n compiler. If this isn't available, it looks for mingw32\n (the gcc compiler).\n\n On Unix, it'll probably use the same compiler that was\n used when compiling Python. Cygwin's behavior should be\n similar.\n verbose -- optional. 0,1, or 2. defualt 0. Speficies how much\n much information is printed during the compile phase\n of inlining code. 0 is silent (except on windows with\n msvc where it still prints some garbage). 1 informs\n you when compiling starts, finishes, and how long it\n took. 2 prints out the command lines for the compilation\n process and can be useful if your having problems\n getting code to work. Its handy for finding the name\n of the .cpp file if you need to examine it. verbose has\n no affect if the compilation isn't necessary.\n support_code -- optional. string. A string of valid C++ code declaring\n extra code that might be needed by your compiled\n function. This could be declarations of functions,\n classes, or structures.\n customize -- optional. base_info.custom_info object. An alternative\n way to specifiy support_code, headers, etc. needed by\n the function see the compiler.base_info module for more\n details. (not sure this'll be used much).\n type_factories -- optional. list of type specification factories. These\n guys are what convert Python data types to C/C++ data\n types. If you'd like to use a different set of type\n conversions than the default, specify them here. Look\n in the type conversions section of the main\n documentation for examples.\n auto_downcast -- optional. 0 or 1. default 1. This only affects\n functions that have Numeric arrays as input variables.\n Setting this to 1 will cause all floating point values\n to be cast as float instead of double if all the\n Numeric arrays are of type float. If even one of the\n arrays has type double or double complex, all\n variables maintain there standard types.\n\n Distutils keywords. These are cut and pasted from Greg Ward's\n distutils.extension.Extension class for convenience:\n\n sources : [string]\n list of source filenames, relative to the distribution root\n (where the setup script lives), in Unix form (slash-separated)\n for portability. Source files may be C, C++, SWIG (.i),\n platform-specific resource files, or whatever else is recognized\n by the \"build_ext\" command as source for a Python extension.\n Note: The module_path file is always appended to the front of this\n list\n include_dirs : [string]\n list of directories to search for C/C++ header files (in Unix\n form for portability)\n define_macros : [(name : string, value : string|None)]\n list of macros to define; each macro is defined using a 2-tuple,\n where 'value' is either the string to define it to or None to\n define it without a particular value (equivalent of \"#define\n FOO\" in source or -DFOO on Unix C compiler command line)\n undef_macros : [string]\n list of macros to undefine explicitly\n library_dirs : [string]\n list of directories to search for C/C++ libraries at link time\n libraries : [string]\n list of library names (not filenames or paths) to link against\n runtime_library_dirs : [string]\n list of directories to search for C/C++ libraries at run time\n (for shared extensions, this is when the extension is loaded)\n extra_objects : [string]\n list of extra files to link with (eg. object files not implied\n by 'sources', static library that must be explicitly specified,\n binary resource files, etc.)\n extra_compile_args : [string]\n any extra platform- and compiler-specific information to use\n when compiling the source files in 'sources'. For platforms and\n compilers where \"command line\" makes sense, this is typically a\n list of command-line arguments, but for other platforms it could\n be anything.\n extra_link_args : [string]\n any extra platform- and compiler-specific information to use\n when linking object files together to create the extension (or\n to create a new static Python interpreter). Similar\n interpretation as for 'extra_compile_args'.\n export_symbols : [string]\n list of symbols to be exported from a shared extension. Not\n used on all platforms, and not generally necessary for Python\n extensions, which typically export exactly one symbol: \"init\" +\n extension_name.\n \"\"\"\n # this grabs the local variables from the *previous* call\n # frame -- that is the locals from the function that called\n # inline.\n global function_catalog\n\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n if force:\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n else:\n # 1. try local cache\n try:\n results = apply(function_cache[code],(local_dict,global_dict))\n return results\n except:\n pass\n\n # 2. try function catalog\n try:\n results = attempt_function_call(code,local_dict,global_dict)\n # 3. build the function\n except ValueError:\n # compile the library\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n return results\n\ndef attempt_function_call(code,local_dict,global_dict):\n # we try 3 levels here -- a local cache first, then the\n # catalog cache, and then persistent catalog.\n #\n global function_cache\n # 2. try catalog cache.\n function_list = function_catalog.get_functions_fast(code)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except TypeError, msg: # should specify argument types here.\n # This should really have its own error type, instead of\n # checking the beginning of the message, but I don't know\n # how to define that yet.\n msg = str(msg)\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n \n # 3. try persistent catalog\n module_dir = global_dict.get('__file__',None)\n function_list = function_catalog.get_functions(code,module_dir)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except: # should specify argument types here.\n pass\n # if we get here, the function wasn't found\n raise ValueError, 'function with correct signature not found'\n\ndef inline_function_code(code,arg_names,local_dict=None,\n global_dict=None,auto_downcast = 1,\n type_factories=None,compiler=''):\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n import build_tools\n compiler = build_tools.choose_compiler(compiler)\n ext_func.set_compiler(compiler)\n return ext_func.function_code()\n\ndef compile_function(code,arg_names,local_dict,global_dict,\n module_dir,\n compiler='',\n verbose = 0,\n support_code = None,\n customize = None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n # figure out where to store and what to name the extension module\n # that will contain the function.\n #storage_dir = catalog.intermediate_dir()\n module_path = function_catalog.unique_module_name(code,module_dir)\n storage_dir, module_name = os.path.split(module_path)\n mod = inline_ext_module(module_name,compiler)\n\n # create the function. This relies on the auto_downcast and\n # type factories setting\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n mod.add_function(ext_func)\n\n # if customize (a custom_info object), then set the module customization.\n if customize:\n mod.customize = customize\n\n # add the extra \"support code\" needed by the function to the module.\n if support_code:\n mod.customize.add_support_code(support_code)\n \n # compile code in correct location, with the given compiler and verbosity\n # setting. All input keywords are passed through to distutils\n mod.compile(location=storage_dir,compiler=compiler,\n verbose=verbose, **kw)\n\n # import the module and return the function. Make sure\n # the directory where it lives is in the python path.\n try:\n sys.path.insert(0,storage_dir)\n exec 'import ' + module_name\n func = eval(module_name+'.compiled_func')\n finally:\n del sys.path[0]\n return func\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\nif __name__ == \"__main__\":\n test_function()\n", "methods": [ { "name": "function_declaration_code", "long_name": "function_declaration_code( self )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 17, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "template_declaration_code", "long_name": "template_declaration_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 16, "parameters": [ "self" ], "start_line": 21, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "parse_tuple_code", "long_name": "parse_tuple_code( self )", "filename": "inline_tools.py", "nloc": 21, "complexity": 3, "token_count": 89, "parameters": [ "self" ], "start_line": 26, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "arg_declaration_code", "long_name": "arg_declaration_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 41, "parameters": [ "self" ], "start_line": 57, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_cleanup_code", "long_name": "arg_cleanup_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 64, "end_line": 69, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_local_dict_code", "long_name": "arg_local_dict_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 71, "end_line": 76, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "inline_tools.py", "nloc": 38, "complexity": 1, "token_count": 148, "parameters": [ "self" ], "start_line": 79, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 122, "end_line": 125, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , compiler = '' )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 35, "parameters": [ "self", "name", "compiler" ], "start_line": 128, "end_line": 130, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "inline", "long_name": "inline( code , arg_names = [ ] , local_dict = None , global_dict = None , force = 0 , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 56, "complexity": 8, "token_count": 295, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "force", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 133, "end_line": 326, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 194, "top_nesting_level": 0 }, { "name": "attempt_function_call", "long_name": "attempt_function_call( code , local_dict , global_dict )", "filename": "inline_tools.py", "nloc": 26, "complexity": 6, "token_count": 143, "parameters": [ "code", "local_dict", "global_dict" ], "start_line": 328, "end_line": 363, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "inline_function_code", "long_name": "inline_function_code( code , arg_names , local_dict = None , global_dict = None , auto_downcast = 1 , type_factories = None , compiler = '' )", "filename": "inline_tools.py", "nloc": 15, "complexity": 3, "token_count": 98, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "auto_downcast", "type_factories", "compiler" ], "start_line": 365, "end_line": 379, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "compile_function", "long_name": "compile_function( code , arg_names , local_dict , global_dict , module_dir , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 29, "complexity": 4, "token_count": 169, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "module_dir", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 381, "end_line": 425, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 45, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 427, "end_line": 429, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 431, "end_line": 433, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "function_declaration_code", "long_name": "function_declaration_code( self )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 17, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "template_declaration_code", "long_name": "template_declaration_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 16, "parameters": [ "self" ], "start_line": 21, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "parse_tuple_code", "long_name": "parse_tuple_code( self )", "filename": "inline_tools.py", "nloc": 21, "complexity": 3, "token_count": 89, "parameters": [ "self" ], "start_line": 26, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "arg_declaration_code", "long_name": "arg_declaration_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 41, "parameters": [ "self" ], "start_line": 57, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_cleanup_code", "long_name": "arg_cleanup_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 64, "end_line": 69, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_local_dict_code", "long_name": "arg_local_dict_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 71, "end_line": 76, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "inline_tools.py", "nloc": 38, "complexity": 1, "token_count": 148, "parameters": [ "self" ], "start_line": 79, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 122, "end_line": 125, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , compiler = '' )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 35, "parameters": [ "self", "name", "compiler" ], "start_line": 128, "end_line": 130, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "inline", "long_name": "inline( code , arg_names = [ ] , local_dict = None , global_dict = None , force = 0 , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 50, "complexity": 6, "token_count": 267, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "force", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 133, "end_line": 321, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 189, "top_nesting_level": 0 }, { "name": "attempt_function_call", "long_name": "attempt_function_call( code , local_dict , global_dict )", "filename": "inline_tools.py", "nloc": 26, "complexity": 6, "token_count": 143, "parameters": [ "code", "local_dict", "global_dict" ], "start_line": 323, "end_line": 358, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "inline_function_code", "long_name": "inline_function_code( code , arg_names , local_dict = None , global_dict = None , auto_downcast = 1 , type_factories = None , compiler = '' )", "filename": "inline_tools.py", "nloc": 15, "complexity": 3, "token_count": 98, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "auto_downcast", "type_factories", "compiler" ], "start_line": 360, "end_line": 374, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "compile_function", "long_name": "compile_function( code , arg_names , local_dict , global_dict , module_dir , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 29, "complexity": 4, "token_count": 169, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "module_dir", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 376, "end_line": 420, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 45, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 422, "end_line": 424, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 426, "end_line": 428, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "inline", "long_name": "inline( code , arg_names = [ ] , local_dict = None , global_dict = None , force = 0 , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 56, "complexity": 8, "token_count": 295, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "force", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 133, "end_line": 326, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 194, "top_nesting_level": 0 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "inline_tools.py", "nloc": 38, "complexity": 1, "token_count": 148, "parameters": [ "self" ], "start_line": 79, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 } ], "nloc": 234, "complexity": 37, "token_count": 1240, "diff_parsed": { "added": [ " catch_code = \"catch(...) \\n\" \\", " \"} \\n\"", " except TypeError, msg: # should specify argument types here.", " msg = str(msg)", " if msg[:16] == \"Conversion Error\":", " pass", " else:", " raise TypeError, msg", " except KeyError:" ], "deleted": [ " catch_code = \"catch( Py::Exception& e) \\n\" \\", " \"} \\n\"", " except:", "" ] } }, { "old_path": "weave/standard_array_info.py", "new_path": "weave/standard_array_info.py", "filename": "standard_array_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -45,7 +45,7 @@\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n- throw Py::TypeError(msg); \n+ throw_error(PyExc_TypeError,msg); \n }\n }\n \n@@ -60,7 +60,7 @@\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n- throw Py::TypeError(msg); \n+ throw_error(PyExc_TypeError,msg); \n }\n }\n \"\"\"\n@@ -74,7 +74,7 @@\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n- throw Py::TypeError(msg);\n+ throw_error(PyExc_TypeError,msg);\n } \n }\n \n@@ -85,7 +85,7 @@\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n- throw Py::TypeError(msg);\n+ throw_error(PyExc_TypeError,msg);\n } \n }\n \"\"\"\n", "added_lines": 4, "deleted_lines": 4, "source_code": "\"\"\" Generic support code for handling standard Numeric arrays \n\"\"\"\n\nimport base_info\n\n\narray_convert_code = \\\n\"\"\"\nstatic PyArrayObject* convert_to_numpy(PyObject* py_obj, char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_conversion_error(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\nstatic PyArrayObject* py_to_numpy(PyObject* py_obj, char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_bad_type(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\n\"\"\"\n\ntype_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\nvoid numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\"\"\"\n\nsize_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\nvoid numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\"\"\"\n\nnumeric_init_code = \\\n\"\"\"\nPy_Initialize();\nimport_array();\nPyImport_ImportModule(\"Numeric\");\n\"\"\"\n\nclass array_info(base_info.base_info):\n _headers = ['\"Numeric/arrayobject.h\"','','']\n _support_code = [array_convert_code,size_check_code, type_check_code]\n _module_init_code = [numeric_init_code] ", "source_code_before": "\"\"\" Generic support code for handling standard Numeric arrays \n\"\"\"\n\nimport base_info\n\n\narray_convert_code = \\\n\"\"\"\nstatic PyArrayObject* convert_to_numpy(PyObject* py_obj, char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_conversion_error(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\nstatic PyArrayObject* py_to_numpy(PyObject* py_obj, char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_bad_type(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\n\"\"\"\n\ntype_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw Py::TypeError(msg); \n }\n}\n\nvoid numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw Py::TypeError(msg); \n }\n}\n\"\"\"\n\nsize_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw Py::TypeError(msg);\n } \n}\n\nvoid numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw Py::TypeError(msg);\n } \n}\n\"\"\"\n\nnumeric_init_code = \\\n\"\"\"\nPy_Initialize();\nimport_array();\nPyImport_ImportModule(\"Numeric\");\n\"\"\"\n\nclass array_info(base_info.base_info):\n _headers = ['\"Numeric/arrayobject.h\"','','']\n _support_code = [array_convert_code,size_check_code, type_check_code]\n _module_init_code = [numeric_init_code] ", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 96, "complexity": 0, "token_count": 50, "diff_parsed": { "added": [ " throw_error(PyExc_TypeError,msg);", " throw_error(PyExc_TypeError,msg);", " throw_error(PyExc_TypeError,msg);", " throw_error(PyExc_TypeError,msg);" ], "deleted": [ " throw Py::TypeError(msg);", " throw Py::TypeError(msg);", " throw Py::TypeError(msg);", " throw Py::TypeError(msg);" ] } }, { "old_path": "weave/tests/test_blitz_tools.py", "new_path": "weave/tests/test_blitz_tools.py", "filename": "test_blitz_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -81,7 +81,8 @@ def generic_test(self,expr,arg_dict,type,size,mod_location):\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n- blitz_tools.blitz(expr,arg_dict,{},verbose=0)\n+ blitz_tools.blitz(expr,arg_dict,{},verbose=2) #,\n+ #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n", "added_lines": 2, "deleted_lines": 1, "source_code": "import unittest\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \nimport RandomArray\nimport os\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path,restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport blitz_tools\nfrom ast_tools import *\nfrom weave_test_utils import *\nrestore_path()\n\nadd_local_to_path(__name__)\nimport test_scalar_spec\nrestore_path()\n\nclass test_ast_to_blitz_expr(unittest.TestCase):\n\n def generic_test(self,expr,desired):\n import parser\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n actual = blitz_tools.ast_to_blitz_expr(ast_list)\n actual = remove_whitespace(actual)\n desired = remove_whitespace(desired)\n print_assert_equal(expr,actual,desired)\n\n def check_simple_expr(self):\n \"\"\"convert simple expr to blitz\n \n a[:1:2] = b[:1+i+2:]\n \"\"\"\n expr = \"a[:1:2] = b[:1+i+2:]\" \n desired = \"a(blitz::Range(_beg,1-1,2))=\"\\\n \"b(blitz::Range(_beg,1+i+2-1));\"\n self.generic_test(expr,desired)\n\n def check_fdtd_expr(self):\n \"\"\" convert fdtd equation to blitz.\n ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] \n + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\n - cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1]);\n Note: This really should have \"\\\" at the end of each line\n to indicate continuation. \n \"\"\"\n expr = \"ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n desired = 'ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))='\\\n ' ca_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' *ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '+cb_y_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hz(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' -hz(_all,blitz::Range(_beg,_Nhz(1)-1-1),_all))'\\\n ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,_Nhy(2)-1-1)));'\n self.generic_test(expr,desired)\n\nclass test_blitz(unittest.TestCase):\n \"\"\"* These are long running tests...\n \n I'd like to benchmark these things somehow.\n *\"\"\"\n def generic_test(self,expr,arg_dict,type,size,mod_location):\n clean_result = array(arg_dict['result'],copy=1)\n t1 = time.time()\n exec expr in globals(),arg_dict\n t2 = time.time()\n standard = t2 - t1\n desired = arg_dict['result']\n arg_dict['result'] = clean_result\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n blitz_tools.blitz(expr,arg_dict,{},verbose=2) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n actual = arg_dict['result']\n # this really should give more info...\n try:\n # this isn't very stringent. Need to tighten this up and\n # learn where failures are occuring.\n assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))\n except:\n diff = actual-desired\n print diff[:4,:4]\n print diff[:4,-4:]\n print diff[-4:,:4]\n print diff[-4:,-4:]\n print sum(abs(diff.flat)) \n raise AssertionError \n return standard,compiled\n \n def generic_2d(self,expr):\n \"\"\" The complex testing is pretty lame...\n \"\"\"\n mod_location = empty_temp_dir()\n import parser\n ast = parser.suite(expr)\n arg_list = harvest_variables(ast.tolist())\n #print arg_list\n all_types = [Float32,Float64,Complex32,Complex64]\n all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)]\n print '\\nExpression:', expr\n for typ in all_types:\n for size in all_sizes:\n result = zeros(size,typ)\n arg_dict = {}\n for arg in arg_list:\n arg_dict[arg] = RandomArray.normal(0,1,size).astype(typ)\n arg_dict[arg].savespace(1)\n # set imag part of complex values to non-zero value\n try: arg_dict[arg].imag = arg_dict[arg].real\n except: pass \n print 'Run:', size,typ\n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1.\n print \"1st run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up) \n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1. \n print \"2nd run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up)\n cleanup_temp_dir(mod_location) \n #def check_simple_2d(self):\n # \"\"\" result = a + b\"\"\" \n # expr = \"result = a + b\"\n # self.generic_2d(expr)\n def check_5point_avg_2d(self):\n \"\"\" result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\n + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n \"\"\" \n expr = \"result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n self.generic_2d(expr)\n \ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_ast_to_blitz_expr,'check_') )\n suites.append( unittest.makeSuite(test_blitz,'check_') ) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "source_code_before": "import unittest\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \nimport RandomArray\nimport os\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path,restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport blitz_tools\nfrom ast_tools import *\nfrom weave_test_utils import *\nrestore_path()\n\nadd_local_to_path(__name__)\nimport test_scalar_spec\nrestore_path()\n\nclass test_ast_to_blitz_expr(unittest.TestCase):\n\n def generic_test(self,expr,desired):\n import parser\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n actual = blitz_tools.ast_to_blitz_expr(ast_list)\n actual = remove_whitespace(actual)\n desired = remove_whitespace(desired)\n print_assert_equal(expr,actual,desired)\n\n def check_simple_expr(self):\n \"\"\"convert simple expr to blitz\n \n a[:1:2] = b[:1+i+2:]\n \"\"\"\n expr = \"a[:1:2] = b[:1+i+2:]\" \n desired = \"a(blitz::Range(_beg,1-1,2))=\"\\\n \"b(blitz::Range(_beg,1+i+2-1));\"\n self.generic_test(expr,desired)\n\n def check_fdtd_expr(self):\n \"\"\" convert fdtd equation to blitz.\n ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] \n + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\n - cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1]);\n Note: This really should have \"\\\" at the end of each line\n to indicate continuation. \n \"\"\"\n expr = \"ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n desired = 'ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))='\\\n ' ca_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' *ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '+cb_y_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hz(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' -hz(_all,blitz::Range(_beg,_Nhz(1)-1-1),_all))'\\\n ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,_Nhy(2)-1-1)));'\n self.generic_test(expr,desired)\n\nclass test_blitz(unittest.TestCase):\n \"\"\"* These are long running tests...\n \n I'd like to benchmark these things somehow.\n *\"\"\"\n def generic_test(self,expr,arg_dict,type,size,mod_location):\n clean_result = array(arg_dict['result'],copy=1)\n t1 = time.time()\n exec expr in globals(),arg_dict\n t2 = time.time()\n standard = t2 - t1\n desired = arg_dict['result']\n arg_dict['result'] = clean_result\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n blitz_tools.blitz(expr,arg_dict,{},verbose=0)\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n actual = arg_dict['result']\n # this really should give more info...\n try:\n # this isn't very stringent. Need to tighten this up and\n # learn where failures are occuring.\n assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))\n except:\n diff = actual-desired\n print diff[:4,:4]\n print diff[:4,-4:]\n print diff[-4:,:4]\n print diff[-4:,-4:]\n print sum(abs(diff.flat)) \n raise AssertionError \n return standard,compiled\n \n def generic_2d(self,expr):\n \"\"\" The complex testing is pretty lame...\n \"\"\"\n mod_location = empty_temp_dir()\n import parser\n ast = parser.suite(expr)\n arg_list = harvest_variables(ast.tolist())\n #print arg_list\n all_types = [Float32,Float64,Complex32,Complex64]\n all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)]\n print '\\nExpression:', expr\n for typ in all_types:\n for size in all_sizes:\n result = zeros(size,typ)\n arg_dict = {}\n for arg in arg_list:\n arg_dict[arg] = RandomArray.normal(0,1,size).astype(typ)\n arg_dict[arg].savespace(1)\n # set imag part of complex values to non-zero value\n try: arg_dict[arg].imag = arg_dict[arg].real\n except: pass \n print 'Run:', size,typ\n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1.\n print \"1st run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up) \n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1. \n print \"2nd run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up)\n cleanup_temp_dir(mod_location) \n #def check_simple_2d(self):\n # \"\"\" result = a + b\"\"\" \n # expr = \"result = a + b\"\n # self.generic_2d(expr)\n def check_5point_avg_2d(self):\n \"\"\" result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\n + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n \"\"\" \n expr = \"result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n self.generic_2d(expr)\n \ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_ast_to_blitz_expr,'check_') )\n suites.append( unittest.makeSuite(test_blitz,'check_') ) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "methods": [ { "name": "generic_test", "long_name": "generic_test( self , expr , desired )", "filename": "test_blitz_tools.py", "nloc": 8, "complexity": 1, "token_count": 54, "parameters": [ "self", "expr", "desired" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "check_simple_expr", "long_name": "check_simple_expr( self )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 36, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "check_fdtd_expr", "long_name": "check_fdtd_expr( self )", "filename": "test_blitz_tools.py", "nloc": 14, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 46, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 21, "top_nesting_level": 1 }, { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 227, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "generic_2d", "long_name": "generic_2d( self , expr )", "filename": "test_blitz_tools.py", "nloc": 35, "complexity": 7, "token_count": 253, "parameters": [ "self", "expr" ], "start_line": 105, "end_line": 143, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "check_5point_avg_2d", "long_name": "check_5point_avg_2d( self )", "filename": "test_blitz_tools.py", "nloc": 4, "complexity": 1, "token_count": 17, "parameters": [ "self" ], "start_line": 148, "end_line": 154, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_blitz_tools.py", "nloc": 6, "complexity": 1, "token_count": 44, "parameters": [], "start_line": 156, "end_line": 161, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 163, "end_line": 167, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "methods_before": [ { "name": "generic_test", "long_name": "generic_test( self , expr , desired )", "filename": "test_blitz_tools.py", "nloc": 8, "complexity": 1, "token_count": 54, "parameters": [ "self", "expr", "desired" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "check_simple_expr", "long_name": "check_simple_expr( self )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 36, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "check_fdtd_expr", "long_name": "check_fdtd_expr( self )", "filename": "test_blitz_tools.py", "nloc": 14, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 46, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 21, "top_nesting_level": 1 }, { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 227, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "generic_2d", "long_name": "generic_2d( self , expr )", "filename": "test_blitz_tools.py", "nloc": 35, "complexity": 7, "token_count": 253, "parameters": [ "self", "expr" ], "start_line": 104, "end_line": 142, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "check_5point_avg_2d", "long_name": "check_5point_avg_2d( self )", "filename": "test_blitz_tools.py", "nloc": 4, "complexity": 1, "token_count": 17, "parameters": [ "self" ], "start_line": 147, "end_line": 153, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_blitz_tools.py", "nloc": 6, "complexity": 1, "token_count": 44, "parameters": [], "start_line": 155, "end_line": 160, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 162, "end_line": 166, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 227, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 } ], "nloc": 131, "complexity": 15, "token_count": 775, "diff_parsed": { "added": [ " blitz_tools.blitz(expr,arg_dict,{},verbose=2) #,", " #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])" ], "deleted": [ " blitz_tools.blitz(expr,arg_dict,{},verbose=0)" ] } }, { "old_path": "weave/tests/test_wx_spec.py", "new_path": "weave/tests/test_wx_spec.py", "filename": "test_wx_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -13,6 +13,7 @@\n \n add_grandparent_to_path(__name__)\n import ext_tools\n+import wx_spec\n restore_path()\n \n import wxPython\n@@ -20,22 +21,22 @@\n \n class test_wx_specification(unittest.TestCase): \n def check_type_match_string(self):\n- s = ext_tools.wx_specification()\n+ s = wx_spec.wx_specification()\n assert(not s.type_match('string') )\n def check_type_match_int(self):\n- s = ext_tools.wx_specification() \n+ s = wx_spec.wx_specification() \n assert(not s.type_match(5))\n def check_type_match_float(self):\n- s = ext_tools.wx_specification() \n+ s = wx_spec.wx_specification() \n assert(not s.type_match(5.))\n def check_type_match_complex(self):\n- s = ext_tools.wx_specification() \n+ s = wx_spec.wx_specification() \n assert(not s.type_match(5.+1j))\n def check_type_match_complex(self):\n- s = ext_tools.wx_specification() \n+ s = wx_spec.wx_specification() \n assert(not s.type_match(5.+1j))\n def check_type_match_wxframe(self):\n- s = ext_tools.wx_specification()\n+ s = wx_spec.wx_specification()\n f=wxPython.wx.wxFrame(wxPython.wx.NULL,-1,'bob') \n assert(s.type_match(f))\n \n@@ -95,7 +96,7 @@ def no_check_return(self):\n def test_suite():\n suites = []\n \n- suites.append( unittest.makeSuite(test_wx_specification,'acheck_'))\n+ suites.append( unittest.makeSuite(test_wx_specification,'check_'))\n total_suite = unittest.TestSuite(suites)\n return total_suite\n \n", "added_lines": 8, "deleted_lines": 7, "source_code": "\"\"\"\ncheck_var_in -- tests whether a variable is passed in correctly\n and also if the passed in variable can be reassigned\ncheck_var_local -- tests wheter a variable is passed in , modified,\n and returned correctly in the local_dict dictionary\n argument\ncheck_return -- test whether a variable is passed in, modified, and\n then returned as a function return value correctly \n\"\"\"\nimport unittest\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path, restore_path\n\nadd_grandparent_to_path(__name__)\nimport ext_tools\nimport wx_spec\nrestore_path()\n\nimport wxPython\nimport wxPython.wx\n\nclass test_wx_specification(unittest.TestCase): \n def check_type_match_string(self):\n s = wx_spec.wx_specification()\n assert(not s.type_match('string') )\n def check_type_match_int(self):\n s = wx_spec.wx_specification() \n assert(not s.type_match(5))\n def check_type_match_float(self):\n s = wx_spec.wx_specification() \n assert(not s.type_match(5.))\n def check_type_match_complex(self):\n s = wx_spec.wx_specification() \n assert(not s.type_match(5.+1j))\n def check_type_match_complex(self):\n s = wx_spec.wx_specification() \n assert(not s.type_match(5.+1j))\n def check_type_match_wxframe(self):\n s = wx_spec.wx_specification()\n f=wxPython.wx.wxFrame(wxPython.wx.NULL,-1,'bob') \n assert(s.type_match(f))\n \n def check_var_in(self):\n mod = ext_tools.ext_module('wx_var_in',compiler='msvc')\n a = wxPython.wx.wxFrame(wxPython.wx.NULL,-1,'bob') \n code = \"\"\"\n a->SetTitle(wxString(\"jim\"));\n \"\"\"\n test = ext_tools.ext_function('test',code,['a'],locals(),globals())\n mod.add_function(test)\n mod.compile()\n import wx_var_in\n b=a\n wx_var_in.test(b)\n assert(b.GetTitle() == \"jim\")\n try:\n b = 1.\n wx_var_in.test(b)\n except TypeError:\n pass\n try:\n b = 1\n wx_var_in.test(b)\n except TypeError:\n pass\n \n def no_check_var_local(self):\n mod = ext_tools.ext_module('wx_var_local')\n a = 'string'\n var_specs = ext_tools.assign_variable_types(['a'],locals())\n code = 'a=Py::String(\"hello\");'\n test = ext_tools.ext_function('test',var_specs,code)\n mod.add_function(test)\n mod.compile()\n import wx_var_local\n b='bub'\n q={}\n wx_var_local.test(b,q)\n assert(q['a'] == 'hello')\n def no_check_return(self):\n mod = ext_tools.ext_module('wx_return')\n a = 'string'\n var_specs = ext_tools.assign_variable_types(['a'],locals())\n code = \"\"\"\n a= Py::wx(\"hello\");\n return_val = Py::new_reference_to(a);\n \"\"\"\n test = ext_tools.ext_function('test',var_specs,code)\n mod.add_function(test)\n mod.compile()\n import wx_return\n b='bub'\n c = wx_return.test(b)\n assert( c == 'hello')\n\ndef test_suite():\n suites = []\n \n suites.append( unittest.makeSuite(test_wx_specification,'check_'))\n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "source_code_before": "\"\"\"\ncheck_var_in -- tests whether a variable is passed in correctly\n and also if the passed in variable can be reassigned\ncheck_var_local -- tests wheter a variable is passed in , modified,\n and returned correctly in the local_dict dictionary\n argument\ncheck_return -- test whether a variable is passed in, modified, and\n then returned as a function return value correctly \n\"\"\"\nimport unittest\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path, restore_path\n\nadd_grandparent_to_path(__name__)\nimport ext_tools\nrestore_path()\n\nimport wxPython\nimport wxPython.wx\n\nclass test_wx_specification(unittest.TestCase): \n def check_type_match_string(self):\n s = ext_tools.wx_specification()\n assert(not s.type_match('string') )\n def check_type_match_int(self):\n s = ext_tools.wx_specification() \n assert(not s.type_match(5))\n def check_type_match_float(self):\n s = ext_tools.wx_specification() \n assert(not s.type_match(5.))\n def check_type_match_complex(self):\n s = ext_tools.wx_specification() \n assert(not s.type_match(5.+1j))\n def check_type_match_complex(self):\n s = ext_tools.wx_specification() \n assert(not s.type_match(5.+1j))\n def check_type_match_wxframe(self):\n s = ext_tools.wx_specification()\n f=wxPython.wx.wxFrame(wxPython.wx.NULL,-1,'bob') \n assert(s.type_match(f))\n \n def check_var_in(self):\n mod = ext_tools.ext_module('wx_var_in',compiler='msvc')\n a = wxPython.wx.wxFrame(wxPython.wx.NULL,-1,'bob') \n code = \"\"\"\n a->SetTitle(wxString(\"jim\"));\n \"\"\"\n test = ext_tools.ext_function('test',code,['a'],locals(),globals())\n mod.add_function(test)\n mod.compile()\n import wx_var_in\n b=a\n wx_var_in.test(b)\n assert(b.GetTitle() == \"jim\")\n try:\n b = 1.\n wx_var_in.test(b)\n except TypeError:\n pass\n try:\n b = 1\n wx_var_in.test(b)\n except TypeError:\n pass\n \n def no_check_var_local(self):\n mod = ext_tools.ext_module('wx_var_local')\n a = 'string'\n var_specs = ext_tools.assign_variable_types(['a'],locals())\n code = 'a=Py::String(\"hello\");'\n test = ext_tools.ext_function('test',var_specs,code)\n mod.add_function(test)\n mod.compile()\n import wx_var_local\n b='bub'\n q={}\n wx_var_local.test(b,q)\n assert(q['a'] == 'hello')\n def no_check_return(self):\n mod = ext_tools.ext_module('wx_return')\n a = 'string'\n var_specs = ext_tools.assign_variable_types(['a'],locals())\n code = \"\"\"\n a= Py::wx(\"hello\");\n return_val = Py::new_reference_to(a);\n \"\"\"\n test = ext_tools.ext_function('test',var_specs,code)\n mod.add_function(test)\n mod.compile()\n import wx_return\n b='bub'\n c = wx_return.test(b)\n assert( c == 'hello')\n\ndef test_suite():\n suites = []\n \n suites.append( unittest.makeSuite(test_wx_specification,'acheck_'))\n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "methods": [ { "name": "check_type_match_string", "long_name": "check_type_match_string( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 23, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_int", "long_name": "check_type_match_int( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 26, "end_line": 28, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_float", "long_name": "check_type_match_float( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 29, "end_line": 31, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_complex", "long_name": "check_type_match_complex( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 32, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_complex", "long_name": "check_type_match_complex( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 35, "end_line": 37, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_wxframe", "long_name": "check_type_match_wxframe( self )", "filename": "test_wx_spec.py", "nloc": 4, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 38, "end_line": 41, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "check_var_in", "long_name": "check_var_in( self )", "filename": "test_wx_spec.py", "nloc": 23, "complexity": 3, "token_count": 124, "parameters": [ "self" ], "start_line": 43, "end_line": 65, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "no_check_var_local", "long_name": "no_check_var_local( self )", "filename": "test_wx_spec.py", "nloc": 13, "complexity": 1, "token_count": 82, "parameters": [ "self" ], "start_line": 67, "end_line": 79, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "no_check_return", "long_name": "no_check_return( self )", "filename": "test_wx_spec.py", "nloc": 15, "complexity": 1, "token_count": 75, "parameters": [ "self" ], "start_line": 80, "end_line": 94, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_wx_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [], "start_line": 96, "end_line": 101, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_wx_spec.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 103, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "methods_before": [ { "name": "check_type_match_string", "long_name": "check_type_match_string( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 22, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_int", "long_name": "check_type_match_int( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 25, "end_line": 27, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_float", "long_name": "check_type_match_float( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 28, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_complex", "long_name": "check_type_match_complex( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_complex", "long_name": "check_type_match_complex( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 34, "end_line": 36, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_wxframe", "long_name": "check_type_match_wxframe( self )", "filename": "test_wx_spec.py", "nloc": 4, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 37, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "check_var_in", "long_name": "check_var_in( self )", "filename": "test_wx_spec.py", "nloc": 23, "complexity": 3, "token_count": 124, "parameters": [ "self" ], "start_line": 42, "end_line": 64, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "no_check_var_local", "long_name": "no_check_var_local( self )", "filename": "test_wx_spec.py", "nloc": 13, "complexity": 1, "token_count": 82, "parameters": [ "self" ], "start_line": 66, "end_line": 78, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "no_check_return", "long_name": "no_check_return( self )", "filename": "test_wx_spec.py", "nloc": 15, "complexity": 1, "token_count": 75, "parameters": [ "self" ], "start_line": 79, "end_line": 93, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_wx_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [], "start_line": 95, "end_line": 100, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_wx_spec.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 102, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "check_type_match_string", "long_name": "check_type_match_string( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 23, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_int", "long_name": "check_type_match_int( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 26, "end_line": 28, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_wx_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [], "start_line": 96, "end_line": 101, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "check_type_match_wxframe", "long_name": "check_type_match_wxframe( self )", "filename": "test_wx_spec.py", "nloc": 4, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 38, "end_line": 41, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "check_type_match_complex", "long_name": "check_type_match_complex( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 32, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_type_match_float", "long_name": "check_type_match_float( self )", "filename": "test_wx_spec.py", "nloc": 3, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 29, "end_line": 31, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 } ], "nloc": 100, "complexity": 13, "token_count": 548, "diff_parsed": { "added": [ "import wx_spec", " s = wx_spec.wx_specification()", " s = wx_spec.wx_specification()", " s = wx_spec.wx_specification()", " s = wx_spec.wx_specification()", " s = wx_spec.wx_specification()", " s = wx_spec.wx_specification()", " suites.append( unittest.makeSuite(test_wx_specification,'check_'))" ], "deleted": [ " s = ext_tools.wx_specification()", " s = ext_tools.wx_specification()", " s = ext_tools.wx_specification()", " s = ext_tools.wx_specification()", " s = ext_tools.wx_specification()", " s = ext_tools.wx_specification()", " suites.append( unittest.makeSuite(test_wx_specification,'acheck_'))" ] } } ] }, { "hash": "a0bf2b3a3ee73b05e2266b9d18de6257ea21366c", "msg": "error in variable name", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T01:51:11+00:00", "author_timezone": 0, "committer_date": "2002-01-17T01:51:11+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "ec1bba279c2b78aa7192a1b047e426b917ac9479" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 1, "lines": 2, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/conversion_code.py", "new_path": "weave/conversion_code.py", "filename": "conversion_code.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -47,7 +47,7 @@\n return \"unkown type\";\n }\n \n-void throw_error(PyObject* py_obj, const char* msg)\n+void throw_error(PyObject* exc, const char* msg)\n {\n PyErr_SetString(exc, msg);\n throw 1;\n", "added_lines": 1, "deleted_lines": 1, "source_code": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nFILE* convert_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nFILE* py_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nPyObject* convert_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nstatic int convert_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long convert_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double convert_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex convert_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "source_code_before": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* py_obj, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nFILE* convert_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nFILE* py_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nPyObject* convert_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nstatic int convert_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long convert_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double convert_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex convert_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 381, "complexity": 0, "token_count": 33, "diff_parsed": { "added": [ "void throw_error(PyObject* exc, const char* msg)" ], "deleted": [ "void throw_error(PyObject* py_obj, const char* msg)" ] } } ] }, { "hash": "6c3253109e966cecb56a3132bc9bb1ec91889083", "msg": "attempt to fix abort with string objects", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T02:48:19+00:00", "author_timezone": 0, "committer_date": "2002-01-17T02:48:19+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "a0bf2b3a3ee73b05e2266b9d18de6257ea21366c" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 2, "insertions": 2, "lines": 4, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/cxx_info.py", "new_path": "weave/cxx_info.py", "filename": "cxx_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -4,14 +4,14 @@\n \"\"\"\n static Py::String convert_to_string(PyObject* py_obj,char* name)\n {\n- if (!PyString_Check(py_obj))\n+ if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n \n static Py::String py_to_string(PyObject* py_obj,char* name)\n {\n- if (!PyString_Check(py_obj))\n+ if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n", "added_lines": 2, "deleted_lines": 2, "source_code": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nstatic Py::String convert_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\nstatic Py::List convert_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nstatic Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nstatic Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "source_code_before": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nstatic Py::String convert_to_string(PyObject* py_obj,char* name)\n{\n if (!PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\nstatic Py::List convert_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nstatic Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nstatic Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 78, "complexity": 0, "token_count": 137, "diff_parsed": { "added": [ " if (!py_obj || !PyString_Check(py_obj))", " if (!py_obj || !PyString_Check(py_obj))" ], "deleted": [ " if (!PyString_Check(py_obj))", " if (!PyString_Check(py_obj))" ] } } ] }, { "hash": "1ed96f36cb3ecfceb682a9a96d3513ed5189a409", "msg": "converted most conversion routines to be class methods so that exceptions won't croak on gcc.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T03:45:05+00:00", "author_timezone": 0, "committer_date": "2002-01-17T03:45:05+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "6c3253109e966cecb56a3132bc9bb1ec91889083" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 133, "insertions": 590, "lines": 723, "files": 5, "dmm_unit_size": 0.0, "dmm_unit_complexity": 1.0, "dmm_unit_interfacing": 0.0, "modified_files": [ { "old_path": "weave/common_spec.py", "new_path": "weave/common_spec.py", "filename": "common_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -26,8 +26,13 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n+ #code = 'PyObject* py_%s = %s;\\n' \\\n+ # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n+ # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n- 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n+ 'file_converter x__;\\n \\\n+ 'PyObject* py_%s = %s;\\n' \\\n+ 'FILE* %s = x__.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n@@ -44,7 +49,10 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n+ #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n+ # (self.name,var_name,self.name)\n+ code = 'callable_converter x__;\\n \\\n+ 'PyObject* %s = x__.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n \n", "added_lines": 10, "deleted_lines": 2, "source_code": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'file_converter x__;\\n \\\n 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'callable_converter x__;\\n \\\n 'PyObject* %s = x__.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 28, "complexity": 1, "token_count": 97, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 59, "end_line": 61, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 63, "end_line": 65, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 6, "complexity": 1, "token_count": 49, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 32, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 33, "end_line": 36, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 23, "parameters": [ "self", "value" ], "start_line": 41, "end_line": 43, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 45, "end_line": 49, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 51, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 55, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 28, "complexity": 1, "token_count": 97, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 } ], "nloc": 54, "complexity": 8, "token_count": 252, "diff_parsed": { "added": [ " #code = 'PyObject* py_%s = %s;\\n' \\", " # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\", " # (self.name,var_name,self.name,self.name,self.name)", " 'file_converter x__;\\n \\", " 'PyObject* py_%s = %s;\\n' \\", " 'FILE* %s = x__.convert_to_file(py_%s,\"%s\");\\n' % \\", " #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\", " # (self.name,var_name,self.name)", " code = 'callable_converter x__;\\n \\", " 'PyObject* %s = x__.convert_to_callable(%s,\"%s\");\\n' % \\" ], "deleted": [ " 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\", " code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\" ] } }, { "old_path": "weave/conversion_code.py", "new_path": "weave/conversion_code.py", "filename": "conversion_code.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -78,25 +78,29 @@\n file_convert_code = \\\n \"\"\"\n \n-FILE* convert_to_file(PyObject* py_obj, char* name)\n+class file_handler\n {\n- if (!py_obj || !PyFile_Check(py_obj))\n- handle_conversion_error(py_obj,\"file\", name);\n-\n- // Cleanup code should call DECREF\n- Py_INCREF(py_obj);\n- return PyFile_AsFile(py_obj);\n-}\n-\n-FILE* py_to_file(PyObject* py_obj, char* name)\n-{\n- if (!py_obj || !PyFile_Check(py_obj))\n- handle_bad_type(py_obj,\"file\", name);\n-\n- // Cleanup code should call DECREF\n- Py_INCREF(py_obj);\n- return PyFile_AsFile(py_obj);\n-}\n+public:\n+ FILE* convert_to_file(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_conversion_error(py_obj,\"file\", name);\n+ \n+ // Cleanup code should call DECREF\n+ Py_INCREF(py_obj);\n+ return PyFile_AsFile(py_obj);\n+ }\n+ \n+ FILE* py_to_file(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_bad_type(py_obj,\"file\", name);\n+ \n+ // Cleanup code should call DECREF\n+ Py_INCREF(py_obj);\n+ return PyFile_AsFile(py_obj);\n+ }\n+};\n \n PyObject* file_to_py(FILE* file, char* name, char* mode)\n {\n@@ -107,6 +111,7 @@\n \n \"\"\"\n \n+\n #############################################################\n # Instance conversion code\n #############################################################\n@@ -114,27 +119,31 @@\n instance_convert_code = \\\n \"\"\"\n \n-PyObject* convert_to_instance(PyObject* py_obj, char* name)\n+class instance_handler\n {\n- if (!py_obj || !PyFile_Check(py_obj))\n- handle_conversion_error(py_obj,\"instance\", name);\n-\n- // Should I INCREF???\n- // Py_INCREF(py_obj);\n- // just return the raw python pointer.\n- return py_obj;\n-}\n-\n-PyObject* py_to_instance(PyObject* py_obj, char* name)\n-{\n- if (!py_obj || !PyFile_Check(py_obj))\n- handle_bad_type(py_obj,\"instance\", name);\n-\n- // Should I INCREF???\n- // Py_INCREF(py_obj);\n- // just return the raw python pointer.\n- return py_obj;\n-}\n+public:\n+ PyObject* convert_to_instance(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_conversion_error(py_obj,\"instance\", name);\n+ \n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+ }\n+ \n+ PyObject* py_to_instance(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_bad_type(py_obj,\"instance\", name);\n+ \n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+ }\n+};\n \n PyObject* instance_to_py(PyObject* instance)\n {\n@@ -151,27 +160,31 @@\n callable_convert_code = \\\n \"\"\"\n \n-PyObject* convert_to_callable(PyObject* py_obj, char* name)\n-{\n- if (!py_obj || !PyCallable_Check(py_obj))\n- handle_conversion_error(py_obj,\"callable\", name);\n-\n- // Should I INCREF???\n- // Py_INCREF(py_obj);\n- // just return the raw python pointer.\n- return py_obj;\n-}\n-\n-PyObject* py_to_callable(PyObject* py_obj, char* name)\n+class callable_handler\n {\n- if (!py_obj || !PyCallable_Check(py_obj))\n- handle_bad_type(py_obj,\"callable\", name);\n-\n- // Should I INCREF???\n- // Py_INCREF(py_obj);\n- // just return the raw python pointer.\n- return py_obj;\n-}\n+public: \n+ PyObject* convert_to_callable(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyCallable_Check(py_obj))\n+ handle_conversion_error(py_obj,\"callable\", name);\n+ \n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+ }\n+ \n+ PyObject* py_to_callable(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyCallable_Check(py_obj))\n+ handle_bad_type(py_obj,\"callable\", name);\n+ \n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+ }\n+};\n \n PyObject* callable_to_py(PyObject* callable)\n {\n@@ -187,27 +200,31 @@\n \n module_convert_code = \\\n \"\"\"\n-PyObject* convert_to_module(PyObject* py_obj, char* name)\n-{\n- if (!py_obj || !PyModule_Check(py_obj))\n- handle_conversion_error(py_obj,\"module\", name);\n-\n- // Should I INCREF???\n- // Py_INCREF(py_obj);\n- // just return the raw python pointer.\n- return py_obj;\n-}\n-\n-PyObject* py_to_module(PyObject* py_obj, char* name)\n+class module_handler\n {\n- if (!py_obj || !PyModule_Check(py_obj))\n- handle_bad_type(py_obj,\"module\", name);\n-\n- // Should I INCREF???\n- // Py_INCREF(py_obj);\n- // just return the raw python pointer.\n- return py_obj;\n-}\n+public:\n+ PyObject* convert_to_module(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyModule_Check(py_obj))\n+ handle_conversion_error(py_obj,\"module\", name);\n+ \n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+ }\n+ \n+ PyObject* py_to_module(PyObject* py_obj, char* name)\n+ {\n+ if (!py_obj || !PyModule_Check(py_obj))\n+ handle_bad_type(py_obj,\"module\", name);\n+ \n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+ }\n+};\n \n PyObject* module_to_py(PyObject* module)\n {\n@@ -349,35 +366,38 @@\n \n // Conversion Errors\n \n-static int convert_to_int(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyInt_Check(py_obj))\n- handle_conversion_error(py_obj,\"int\", name);\n- return (int) PyInt_AsLong(py_obj);\n-}\n-\n-static long convert_to_long(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyLong_Check(py_obj))\n- handle_conversion_error(py_obj,\"long\", name);\n- return (long) PyLong_AsLong(py_obj);\n-}\n-\n-static double convert_to_float(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyFloat_Check(py_obj))\n- handle_conversion_error(py_obj,\"float\", name);\n- return PyFloat_AsDouble(py_obj);\n-}\n+class scalar_handler\n+{\n+public: \n+ int convert_to_int(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_conversion_error(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+ }\n+ long convert_to_long(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_conversion_error(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+ }\n+\n+ double convert_to_float(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_conversion_error(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+ }\n \n // complex not checked.\n-static std::complex convert_to_complex(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyComplex_Check(py_obj))\n- handle_conversion_error(py_obj,\"complex\", name);\n- return std::complex(PyComplex_RealAsDouble(py_obj),\n- PyComplex_ImagAsDouble(py_obj)); \n-}\n+ std::complex convert_to_complex(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_conversion_error(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+ }\n+};\n \n /////////////////////////////////////\n // The following functions are used for scalar conversions in msvc\n", "added_lines": 125, "deleted_lines": 105, "source_code": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nclass file_handler\n{\npublic:\n FILE* convert_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n \n FILE* py_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n};\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nclass instance_handler\n{\npublic:\n PyObject* convert_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nclass callable_handler\n{\npublic: \n PyObject* convert_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nclass module_handler\n{\npublic:\n PyObject* convert_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nclass scalar_handler\n{\npublic: \n int convert_to_int(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n }\n long convert_to_long(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n }\n\n double convert_to_float(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n }\n\n// complex not checked.\n std::complex convert_to_complex(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n }\n};\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "source_code_before": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nFILE* convert_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nFILE* py_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nPyObject* convert_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nstatic int convert_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long convert_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double convert_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex convert_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 400, "complexity": 0, "token_count": 33, "diff_parsed": { "added": [ "class file_handler", "public:", " FILE* convert_to_file(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyFile_Check(py_obj))", " handle_conversion_error(py_obj,\"file\", name);", "", " // Cleanup code should call DECREF", " Py_INCREF(py_obj);", " return PyFile_AsFile(py_obj);", " }", "", " FILE* py_to_file(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyFile_Check(py_obj))", " handle_bad_type(py_obj,\"file\", name);", "", " // Cleanup code should call DECREF", " Py_INCREF(py_obj);", " return PyFile_AsFile(py_obj);", " }", "};", "", "class instance_handler", "public:", " PyObject* convert_to_instance(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyFile_Check(py_obj))", " handle_conversion_error(py_obj,\"instance\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", " }", "", " PyObject* py_to_instance(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyFile_Check(py_obj))", " handle_bad_type(py_obj,\"instance\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", " }", "};", "class callable_handler", "public:", " PyObject* convert_to_callable(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyCallable_Check(py_obj))", " handle_conversion_error(py_obj,\"callable\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", " }", "", " PyObject* py_to_callable(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyCallable_Check(py_obj))", " handle_bad_type(py_obj,\"callable\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", " }", "};", "class module_handler", "public:", " PyObject* convert_to_module(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyModule_Check(py_obj))", " handle_conversion_error(py_obj,\"module\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", " }", "", " PyObject* py_to_module(PyObject* py_obj, char* name)", " {", " if (!py_obj || !PyModule_Check(py_obj))", " handle_bad_type(py_obj,\"module\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", " }", "};", "class scalar_handler", "{", "public:", " int convert_to_int(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyInt_Check(py_obj))", " handle_conversion_error(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", " }", " long convert_to_long(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyLong_Check(py_obj))", " handle_conversion_error(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", " }", "", " double convert_to_float(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_conversion_error(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", " }", " std::complex convert_to_complex(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", " }", "};" ], "deleted": [ "FILE* convert_to_file(PyObject* py_obj, char* name)", " if (!py_obj || !PyFile_Check(py_obj))", " handle_conversion_error(py_obj,\"file\", name);", "", " // Cleanup code should call DECREF", " Py_INCREF(py_obj);", " return PyFile_AsFile(py_obj);", "}", "", "FILE* py_to_file(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyFile_Check(py_obj))", " handle_bad_type(py_obj,\"file\", name);", "", " // Cleanup code should call DECREF", " Py_INCREF(py_obj);", " return PyFile_AsFile(py_obj);", "}", "PyObject* convert_to_instance(PyObject* py_obj, char* name)", " if (!py_obj || !PyFile_Check(py_obj))", " handle_conversion_error(py_obj,\"instance\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* py_to_instance(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyFile_Check(py_obj))", " handle_bad_type(py_obj,\"instance\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "PyObject* convert_to_callable(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyCallable_Check(py_obj))", " handle_conversion_error(py_obj,\"callable\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* py_to_callable(PyObject* py_obj, char* name)", " if (!py_obj || !PyCallable_Check(py_obj))", " handle_bad_type(py_obj,\"callable\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "PyObject* convert_to_module(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyModule_Check(py_obj))", " handle_conversion_error(py_obj,\"module\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* py_to_module(PyObject* py_obj, char* name)", " if (!py_obj || !PyModule_Check(py_obj))", " handle_bad_type(py_obj,\"module\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "static int convert_to_int(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyInt_Check(py_obj))", " handle_conversion_error(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", "}", "", "static long convert_to_long(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyLong_Check(py_obj))", " handle_conversion_error(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", "}", "", "static double convert_to_float(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_conversion_error(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", "}", "static std::complex convert_to_complex(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", "}" ] } }, { "old_path": null, "new_path": "weave/conversion_code_old.py", "filename": "conversion_code_old.py", "extension": "py", "change_type": "ADD", "diff": "@@ -0,0 +1,415 @@\n+\"\"\" C/C++ code strings needed for converting most non-sequence\n+ Python variables:\n+ module_support_code -- several routines used by most other code \n+ conversion methods. It holds the only\n+ CXX dependent code in this file. The CXX\n+ stuff is used for exceptions\n+ file_convert_code\n+ instance_convert_code\n+ callable_convert_code\n+ module_convert_code\n+ \n+ scalar_convert_code\n+ non_template_scalar_support_code \n+ Scalar conversion covers int, float, double, complex,\n+ and double complex. While Python doesn't support all these,\n+ Numeric does and so all of them are made available.\n+ Python longs are currently converted to C ints. Any\n+ better way to handle this?\n+\"\"\"\n+\n+import base_info\n+\n+#############################################################\n+# Basic module support code\n+#############################################################\n+\n+module_support_code = \\\n+\"\"\"\n+\n+char* find_type(PyObject* py_obj)\n+{\n+ if(py_obj == NULL) return \"C NULL value\";\n+ if(PyCallable_Check(py_obj)) return \"callable\";\n+ if(PyString_Check(py_obj)) return \"string\";\n+ if(PyInt_Check(py_obj)) return \"int\";\n+ if(PyFloat_Check(py_obj)) return \"float\";\n+ if(PyDict_Check(py_obj)) return \"dict\";\n+ if(PyList_Check(py_obj)) return \"list\";\n+ if(PyTuple_Check(py_obj)) return \"tuple\";\n+ if(PyFile_Check(py_obj)) return \"file\";\n+ if(PyModule_Check(py_obj)) return \"module\";\n+ \n+ //should probably do more intergation (and thinking) on these.\n+ if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n+ if(PyInstance_Check(py_obj)) return \"instance\"; \n+ if(PyCallable_Check(py_obj)) return \"callable\";\n+ return \"unkown type\";\n+}\n+\n+void throw_error(PyObject* exc, const char* msg)\n+{\n+ PyErr_SetString(exc, msg);\n+ throw 1;\n+}\n+\n+void handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n+{\n+ char msg[500];\n+ sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n+ find_type(py_obj),good_type,var_name);\n+ throw_error(PyExc_TypeError,msg); \n+}\n+\n+void handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n+{\n+ char msg[500];\n+ sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n+ find_type(py_obj),good_type,var_name);\n+ throw_error(PyExc_TypeError,msg);\n+}\n+\n+\"\"\"\n+\n+#############################################################\n+# File conversion support code\n+#############################################################\n+\n+file_convert_code = \\\n+\"\"\"\n+\n+FILE* convert_to_file(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_conversion_error(py_obj,\"file\", name);\n+\n+ // Cleanup code should call DECREF\n+ Py_INCREF(py_obj);\n+ return PyFile_AsFile(py_obj);\n+}\n+\n+FILE* py_to_file(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_bad_type(py_obj,\"file\", name);\n+\n+ // Cleanup code should call DECREF\n+ Py_INCREF(py_obj);\n+ return PyFile_AsFile(py_obj);\n+}\n+\n+PyObject* file_to_py(FILE* file, char* name, char* mode)\n+{\n+ PyObject* py_obj = NULL;\n+ //extern int fclose(FILE *);\n+ return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n+}\n+\n+\"\"\"\n+\n+#############################################################\n+# Instance conversion code\n+#############################################################\n+\n+instance_convert_code = \\\n+\"\"\"\n+\n+PyObject* convert_to_instance(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_conversion_error(py_obj,\"instance\", name);\n+\n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+}\n+\n+PyObject* py_to_instance(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyFile_Check(py_obj))\n+ handle_bad_type(py_obj,\"instance\", name);\n+\n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+}\n+\n+PyObject* instance_to_py(PyObject* instance)\n+{\n+ // Don't think I need to do anything...\n+ return (PyObject*) instance;\n+}\n+\n+\"\"\"\n+\n+#############################################################\n+# Callable conversion code\n+#############################################################\n+\n+callable_convert_code = \\\n+\"\"\"\n+\n+PyObject* convert_to_callable(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyCallable_Check(py_obj))\n+ handle_conversion_error(py_obj,\"callable\", name);\n+\n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+}\n+\n+PyObject* py_to_callable(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyCallable_Check(py_obj))\n+ handle_bad_type(py_obj,\"callable\", name);\n+\n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+}\n+\n+PyObject* callable_to_py(PyObject* callable)\n+{\n+ // Don't think I need to do anything...\n+ return (PyObject*) callable;\n+}\n+\n+\"\"\"\n+\n+#############################################################\n+# Module conversion code\n+#############################################################\n+\n+module_convert_code = \\\n+\"\"\"\n+PyObject* convert_to_module(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyModule_Check(py_obj))\n+ handle_conversion_error(py_obj,\"module\", name);\n+\n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+}\n+\n+PyObject* py_to_module(PyObject* py_obj, char* name)\n+{\n+ if (!py_obj || !PyModule_Check(py_obj))\n+ handle_bad_type(py_obj,\"module\", name);\n+\n+ // Should I INCREF???\n+ // Py_INCREF(py_obj);\n+ // just return the raw python pointer.\n+ return py_obj;\n+}\n+\n+PyObject* module_to_py(PyObject* module)\n+{\n+ // Don't think I need to do anything...\n+ return (PyObject*) module;\n+}\n+\n+\"\"\"\n+\n+#############################################################\n+# Scalar conversion code\n+#############################################################\n+\n+import base_info\n+\n+# this code will not build with msvc...\n+scalar_support_code = \\\n+\"\"\"\n+// conversion routines\n+\n+template \n+static T convert_to_scalar(PyObject* py_obj,char* name)\n+{\n+ //never used.\n+ return (T) 0;\n+}\n+template<>\n+static int convert_to_scalar(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_conversion_error(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+}\n+\n+template<>\n+static long convert_to_scalar(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_conversion_error(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+}\n+\n+template<> \n+static double convert_to_scalar(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_conversion_error(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+}\n+\n+template<> \n+static float convert_to_scalar(PyObject* py_obj,char* name)\n+{\n+ return (float) convert_to_scalar(py_obj,name);\n+}\n+\n+// complex not checked.\n+template<> \n+static std::complex convert_to_scalar >(PyObject* py_obj,\n+ char* name)\n+{\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_conversion_error(py_obj,\"complex\", name);\n+ return std::complex((float) PyComplex_RealAsDouble(py_obj),\n+ (float) PyComplex_ImagAsDouble(py_obj)); \n+}\n+template<> \n+static std::complex convert_to_scalar >(\n+ PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_conversion_error(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+}\n+\n+/////////////////////////////////\n+// standard translation routines\n+\n+template \n+static T py_to_scalar(PyObject* py_obj,char* name)\n+{\n+ //never used.\n+ return (T) 0;\n+}\n+template<>\n+static int py_to_scalar(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_bad_type(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+}\n+\n+template<>\n+static long py_to_scalar(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_bad_type(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+}\n+\n+template<> \n+static double py_to_scalar(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_bad_type(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+}\n+\n+template<> \n+static float py_to_scalar(PyObject* py_obj,char* name)\n+{\n+ return (float) py_to_scalar(py_obj,name);\n+}\n+\n+// complex not checked.\n+template<> \n+static std::complex py_to_scalar >(PyObject* py_obj,\n+ char* name)\n+{\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_bad_type(py_obj,\"complex\", name);\n+ return std::complex((float) PyComplex_RealAsDouble(py_obj),\n+ (float) PyComplex_ImagAsDouble(py_obj)); \n+}\n+template<> \n+static std::complex py_to_scalar >(\n+ PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_bad_type(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+}\n+\"\"\" \n+\n+non_template_scalar_support_code = \\\n+\"\"\"\n+\n+// Conversion Errors\n+\n+static int convert_to_int(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_conversion_error(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+}\n+\n+static long convert_to_long(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_conversion_error(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+}\n+\n+static double convert_to_float(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_conversion_error(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+}\n+\n+// complex not checked.\n+static std::complex convert_to_complex(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_conversion_error(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+}\n+\n+/////////////////////////////////////\n+// The following functions are used for scalar conversions in msvc\n+// because it doesn't handle templates as well.\n+\n+static int py_to_int(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_bad_type(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+}\n+\n+static long py_to_long(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_bad_type(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+}\n+\n+static double py_to_float(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_bad_type(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+}\n+\n+// complex not checked.\n+static std::complex py_to_complex(PyObject* py_obj,char* name)\n+{\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_bad_type(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+}\n+\"\"\" \n", "added_lines": 415, "deleted_lines": 0, "source_code": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nFILE* convert_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nFILE* py_to_file(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n\n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n}\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_instance(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nPyObject* convert_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_callable(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nPyObject* convert_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* py_to_module(PyObject* py_obj, char* name)\n{\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n\n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n}\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nstatic int convert_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long convert_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double convert_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex convert_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "source_code_before": null, "methods": [], "methods_before": [], "changed_methods": [], "nloc": 381, "complexity": 0, "token_count": 33, "diff_parsed": { "added": [ "\"\"\" C/C++ code strings needed for converting most non-sequence", " Python variables:", " module_support_code -- several routines used by most other code", " conversion methods. It holds the only", " CXX dependent code in this file. The CXX", " stuff is used for exceptions", " file_convert_code", " instance_convert_code", " callable_convert_code", " module_convert_code", "", " scalar_convert_code", " non_template_scalar_support_code", " Scalar conversion covers int, float, double, complex,", " and double complex. While Python doesn't support all these,", " Numeric does and so all of them are made available.", " Python longs are currently converted to C ints. Any", " better way to handle this?", "\"\"\"", "", "import base_info", "", "#############################################################", "# Basic module support code", "#############################################################", "", "module_support_code = \\", "\"\"\"", "", "char* find_type(PyObject* py_obj)", "{", " if(py_obj == NULL) return \"C NULL value\";", " if(PyCallable_Check(py_obj)) return \"callable\";", " if(PyString_Check(py_obj)) return \"string\";", " if(PyInt_Check(py_obj)) return \"int\";", " if(PyFloat_Check(py_obj)) return \"float\";", " if(PyDict_Check(py_obj)) return \"dict\";", " if(PyList_Check(py_obj)) return \"list\";", " if(PyTuple_Check(py_obj)) return \"tuple\";", " if(PyFile_Check(py_obj)) return \"file\";", " if(PyModule_Check(py_obj)) return \"module\";", "", " //should probably do more intergation (and thinking) on these.", " if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";", " if(PyInstance_Check(py_obj)) return \"instance\";", " if(PyCallable_Check(py_obj)) return \"callable\";", " return \"unkown type\";", "}", "", "void throw_error(PyObject* exc, const char* msg)", "{", " PyErr_SetString(exc, msg);", " throw 1;", "}", "", "void handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)", "{", " char msg[500];", " sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",", " find_type(py_obj),good_type,var_name);", " throw_error(PyExc_TypeError,msg);", "}", "", "void handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)", "{", " char msg[500];", " sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",", " find_type(py_obj),good_type,var_name);", " throw_error(PyExc_TypeError,msg);", "}", "", "\"\"\"", "", "#############################################################", "# File conversion support code", "#############################################################", "", "file_convert_code = \\", "\"\"\"", "", "FILE* convert_to_file(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyFile_Check(py_obj))", " handle_conversion_error(py_obj,\"file\", name);", "", " // Cleanup code should call DECREF", " Py_INCREF(py_obj);", " return PyFile_AsFile(py_obj);", "}", "", "FILE* py_to_file(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyFile_Check(py_obj))", " handle_bad_type(py_obj,\"file\", name);", "", " // Cleanup code should call DECREF", " Py_INCREF(py_obj);", " return PyFile_AsFile(py_obj);", "}", "", "PyObject* file_to_py(FILE* file, char* name, char* mode)", "{", " PyObject* py_obj = NULL;", " //extern int fclose(FILE *);", " return (PyObject*) PyFile_FromFile(file, name, mode, fclose);", "}", "", "\"\"\"", "", "#############################################################", "# Instance conversion code", "#############################################################", "", "instance_convert_code = \\", "\"\"\"", "", "PyObject* convert_to_instance(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyFile_Check(py_obj))", " handle_conversion_error(py_obj,\"instance\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* py_to_instance(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyFile_Check(py_obj))", " handle_bad_type(py_obj,\"instance\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* instance_to_py(PyObject* instance)", "{", " // Don't think I need to do anything...", " return (PyObject*) instance;", "}", "", "\"\"\"", "", "#############################################################", "# Callable conversion code", "#############################################################", "", "callable_convert_code = \\", "\"\"\"", "", "PyObject* convert_to_callable(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyCallable_Check(py_obj))", " handle_conversion_error(py_obj,\"callable\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* py_to_callable(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyCallable_Check(py_obj))", " handle_bad_type(py_obj,\"callable\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* callable_to_py(PyObject* callable)", "{", " // Don't think I need to do anything...", " return (PyObject*) callable;", "}", "", "\"\"\"", "", "#############################################################", "# Module conversion code", "#############################################################", "", "module_convert_code = \\", "\"\"\"", "PyObject* convert_to_module(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyModule_Check(py_obj))", " handle_conversion_error(py_obj,\"module\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* py_to_module(PyObject* py_obj, char* name)", "{", " if (!py_obj || !PyModule_Check(py_obj))", " handle_bad_type(py_obj,\"module\", name);", "", " // Should I INCREF???", " // Py_INCREF(py_obj);", " // just return the raw python pointer.", " return py_obj;", "}", "", "PyObject* module_to_py(PyObject* module)", "{", " // Don't think I need to do anything...", " return (PyObject*) module;", "}", "", "\"\"\"", "", "#############################################################", "# Scalar conversion code", "#############################################################", "", "import base_info", "", "# this code will not build with msvc...", "scalar_support_code = \\", "\"\"\"", "// conversion routines", "", "template", "static T convert_to_scalar(PyObject* py_obj,char* name)", "{", " //never used.", " return (T) 0;", "}", "template<>", "static int convert_to_scalar(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyInt_Check(py_obj))", " handle_conversion_error(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", "}", "", "template<>", "static long convert_to_scalar(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyLong_Check(py_obj))", " handle_conversion_error(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", "}", "", "template<>", "static double convert_to_scalar(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_conversion_error(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", "}", "", "template<>", "static float convert_to_scalar(PyObject* py_obj,char* name)", "{", " return (float) convert_to_scalar(py_obj,name);", "}", "", "// complex not checked.", "template<>", "static std::complex convert_to_scalar >(PyObject* py_obj,", " char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex((float) PyComplex_RealAsDouble(py_obj),", " (float) PyComplex_ImagAsDouble(py_obj));", "}", "template<>", "static std::complex convert_to_scalar >(", " PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", "}", "", "/////////////////////////////////", "// standard translation routines", "", "template", "static T py_to_scalar(PyObject* py_obj,char* name)", "{", " //never used.", " return (T) 0;", "}", "template<>", "static int py_to_scalar(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyInt_Check(py_obj))", " handle_bad_type(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", "}", "", "template<>", "static long py_to_scalar(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyLong_Check(py_obj))", " handle_bad_type(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", "}", "", "template<>", "static double py_to_scalar(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_bad_type(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", "}", "", "template<>", "static float py_to_scalar(PyObject* py_obj,char* name)", "{", " return (float) py_to_scalar(py_obj,name);", "}", "", "// complex not checked.", "template<>", "static std::complex py_to_scalar >(PyObject* py_obj,", " char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_bad_type(py_obj,\"complex\", name);", " return std::complex((float) PyComplex_RealAsDouble(py_obj),", " (float) PyComplex_ImagAsDouble(py_obj));", "}", "template<>", "static std::complex py_to_scalar >(", " PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_bad_type(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", "}", "\"\"\"", "", "non_template_scalar_support_code = \\", "\"\"\"", "", "// Conversion Errors", "", "static int convert_to_int(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyInt_Check(py_obj))", " handle_conversion_error(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", "}", "", "static long convert_to_long(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyLong_Check(py_obj))", " handle_conversion_error(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", "}", "", "static double convert_to_float(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_conversion_error(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", "}", "", "// complex not checked.", "static std::complex convert_to_complex(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", "}", "", "/////////////////////////////////////", "// The following functions are used for scalar conversions in msvc", "// because it doesn't handle templates as well.", "", "static int py_to_int(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyInt_Check(py_obj))", " handle_bad_type(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", "}", "", "static long py_to_long(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyLong_Check(py_obj))", " handle_bad_type(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", "}", "", "static double py_to_float(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_bad_type(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", "}", "", "// complex not checked.", "static std::complex py_to_complex(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_bad_type(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", "}", "\"\"\"" ], "deleted": [] } }, { "old_path": "weave/cxx_info.py", "new_path": "weave/cxx_info.py", "filename": "cxx_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -2,13 +2,15 @@\n \n string_support_code = \\\n \"\"\"\n-static Py::String convert_to_string(PyObject* py_obj,char* name)\n+class string_handler\n {\n- if (!py_obj || !PyString_Check(py_obj))\n- handle_conversion_error(py_obj,\"string\", name);\n- return Py::String(py_obj);\n-}\n-\n+ static Py::String convert_to_string(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyString_Check(py_obj))\n+ handle_conversion_error(py_obj,\"string\", name);\n+ return Py::String(py_obj);\n+ }\n+};\n static Py::String py_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n@@ -20,12 +22,16 @@\n \n list_support_code = \\\n \"\"\"\n-static Py::List convert_to_list(PyObject* py_obj,char* name)\n+\n+class list_handler\n {\n- if (!py_obj || !PyList_Check(py_obj))\n- handle_conversion_error(py_obj,\"list\", name);\n- return Py::List(py_obj);\n-}\n+ Py::List convert_to_list(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyList_Check(py_obj))\n+ handle_conversion_error(py_obj,\"list\", name);\n+ return Py::List(py_obj);\n+ }\n+};\n \n static Py::List py_to_list(PyObject* py_obj,char* name)\n {\n@@ -37,11 +43,14 @@\n \n dict_support_code = \\\n \"\"\"\n-static Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n+class dict_handler\n {\n- if (!py_obj || !PyDict_Check(py_obj))\n- handle_conversion_error(py_obj,\"dict\", name);\n- return Py::Dict(py_obj);\n+ Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyDict_Check(py_obj))\n+ handle_conversion_error(py_obj,\"dict\", name);\n+ return Py::Dict(py_obj);\n+ }\n }\n \n static Py::Dict py_to_dict(PyObject* py_obj,char* name)\n@@ -54,12 +63,15 @@\n \n tuple_support_code = \\\n \"\"\"\n-static Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n+class tuple_handler\n {\n- if (!py_obj || !PyTuple_Check(py_obj))\n- handle_conversion_error(py_obj,\"tuple\", name);\n- return Py::Tuple(py_obj);\n-}\n+ Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n+ {\n+ if (!py_obj || !PyTuple_Check(py_obj))\n+ handle_conversion_error(py_obj,\"tuple\", name);\n+ return Py::Tuple(py_obj);\n+ }\n+};\n \n static Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n {\n", "added_lines": 32, "deleted_lines": 20, "source_code": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\n static Py::String convert_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\n Py::List convert_to_list(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\n Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n}\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\n Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "source_code_before": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nstatic Py::String convert_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\nstatic Py::List convert_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nstatic Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nstatic Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 90, "complexity": 0, "token_count": 137, "diff_parsed": { "added": [ "class string_handler", " static Py::String convert_to_string(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyString_Check(py_obj))", " handle_conversion_error(py_obj,\"string\", name);", " return Py::String(py_obj);", " }", "};", "", "class list_handler", " Py::List convert_to_list(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyList_Check(py_obj))", " handle_conversion_error(py_obj,\"list\", name);", " return Py::List(py_obj);", " }", "};", "class dict_handler", " Py::Dict convert_to_dict(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyDict_Check(py_obj))", " handle_conversion_error(py_obj,\"dict\", name);", " return Py::Dict(py_obj);", " }", "class tuple_handler", " Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyTuple_Check(py_obj))", " handle_conversion_error(py_obj,\"tuple\", name);", " return Py::Tuple(py_obj);", " }", "};" ], "deleted": [ "static Py::String convert_to_string(PyObject* py_obj,char* name)", " if (!py_obj || !PyString_Check(py_obj))", " handle_conversion_error(py_obj,\"string\", name);", " return Py::String(py_obj);", "}", "", "static Py::List convert_to_list(PyObject* py_obj,char* name)", " if (!py_obj || !PyList_Check(py_obj))", " handle_conversion_error(py_obj,\"list\", name);", " return Py::List(py_obj);", "}", "static Py::Dict convert_to_dict(PyObject* py_obj,char* name)", " if (!py_obj || !PyDict_Check(py_obj))", " handle_conversion_error(py_obj,\"dict\", name);", " return Py::Dict(py_obj);", "static Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)", " if (!py_obj || !PyTuple_Check(py_obj))", " handle_conversion_error(py_obj,\"tuple\", name);", " return Py::Tuple(py_obj);", "}" ] } }, { "old_path": "weave/scalar_spec.py", "new_path": "weave/scalar_spec.py", "filename": "scalar_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -40,10 +40,11 @@ def type_spec(self,name,value):\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n- if self.compiler == 'msvc':\n- return self.msvc_decl_code(templatize,inline)\n- else:\n- return self.template_decl_code(templatize,inline) \n+ #if self.compiler == 'msvc':\n+ # return self.msvc_decl_code(templatize,inline)\n+ #else:\n+ # return self.template_decl_code(templatize,inline) \\\n+ return self.msvc_decl_code(templatize,inline)\n \n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n@@ -63,8 +64,9 @@ def msvc_decl_code(self,template = 0,inline=0):\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n- template = '%(type)s %(name)s = '\\\n- 'convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n+ template = 'scalar_handler x__; \\n' \\\n+ '%(type)s %(name)s = '\\\n+ 'x__convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n", "added_lines": 8, "deleted_lines": 6, "source_code": "from base_spec import base_specification\nimport scalar_info\n#from Numeric import *\nfrom types import *\n\n# the following typemaps are for 32 bit platforms. A way to do this\n# general case? maybe ask numeric types how long they are and base\n# the decisions on that.\n\nnumeric_to_blitz_type_mapping = {}\n\nnumeric_to_blitz_type_mapping['T'] = 'T' # for templates\nnumeric_to_blitz_type_mapping['F'] = 'std::complex '\nnumeric_to_blitz_type_mapping['D'] = 'std::complex '\nnumeric_to_blitz_type_mapping['f'] = 'float'\nnumeric_to_blitz_type_mapping['d'] = 'double'\nnumeric_to_blitz_type_mapping['1'] = 'char'\nnumeric_to_blitz_type_mapping['b'] = 'unsigned char'\nnumeric_to_blitz_type_mapping['s'] = 'short'\nnumeric_to_blitz_type_mapping['i'] = 'int'\n# not strictly correct, but shoulld be fine fo numeric work.\n# add test somewhere to make sure long can be cast to int before using.\nnumeric_to_blitz_type_mapping['l'] = 'int'\n\n# standard Python numeric type mappings.\nnumeric_to_blitz_type_mapping[type(1)] = 'int'\nnumeric_to_blitz_type_mapping[type(1.)] = 'double'\nnumeric_to_blitz_type_mapping[type(1.+1.j)] = 'std::complex '\n#hmmm. The following is likely unsafe...\nnumeric_to_blitz_type_mapping[type(1L)] = 'int'\n\nclass scalar_specification(base_specification):\n _build_information = [scalar_info.scalar_info()] \n\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name\n new_spec.numeric_type = type(value)\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n #if self.compiler == 'msvc':\n # return self.msvc_decl_code(templatize,inline)\n #else:\n # return self.template_decl_code(templatize,inline) \\\n return self.msvc_decl_code(templatize,inline)\n\n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_scalar<%(type)s >(%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n ValueError, 'msvc compiler does not support templated scalar code.'\\\n 'try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = 'scalar_handler x__; \\n' \\\n '%(type)s %(name)s = '\\\n 'x__convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n\n #def c_function_declaration_code(self):\n # code = '%s &%s\" % \\\n # (numeric_to_blitz_type_mapping[self.numeric_type], self.name)\n # return code\n\n def __repr__(self):\n msg = \"(%s:: name: %s, type: %s)\" % \\\n (self.type_name,self.name, self.numeric_type)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.__class__, other.__class__)\n\nclass int_specification(scalar_specification):\n type_name = 'int'\n def type_match(self,value):\n return type(value) in [IntType, LongType]\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Int(%s);\\n' % (self.name,self.name) \n return code\n \nclass float_specification(scalar_specification):\n type_name = 'float'\n def type_match(self,value):\n return type(value) in [FloatType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Float(%s);\\n' % (self.name,self.name) \n return code\n\nclass complex_specification(scalar_specification):\n type_name = 'complex'\n def type_match(self,value):\n return type(value) in [ComplexType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Complex(%s.real(),%s.imag());\\n' % \\\n (self.name,self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n ", "source_code_before": "from base_spec import base_specification\nimport scalar_info\n#from Numeric import *\nfrom types import *\n\n# the following typemaps are for 32 bit platforms. A way to do this\n# general case? maybe ask numeric types how long they are and base\n# the decisions on that.\n\nnumeric_to_blitz_type_mapping = {}\n\nnumeric_to_blitz_type_mapping['T'] = 'T' # for templates\nnumeric_to_blitz_type_mapping['F'] = 'std::complex '\nnumeric_to_blitz_type_mapping['D'] = 'std::complex '\nnumeric_to_blitz_type_mapping['f'] = 'float'\nnumeric_to_blitz_type_mapping['d'] = 'double'\nnumeric_to_blitz_type_mapping['1'] = 'char'\nnumeric_to_blitz_type_mapping['b'] = 'unsigned char'\nnumeric_to_blitz_type_mapping['s'] = 'short'\nnumeric_to_blitz_type_mapping['i'] = 'int'\n# not strictly correct, but shoulld be fine fo numeric work.\n# add test somewhere to make sure long can be cast to int before using.\nnumeric_to_blitz_type_mapping['l'] = 'int'\n\n# standard Python numeric type mappings.\nnumeric_to_blitz_type_mapping[type(1)] = 'int'\nnumeric_to_blitz_type_mapping[type(1.)] = 'double'\nnumeric_to_blitz_type_mapping[type(1.+1.j)] = 'std::complex '\n#hmmm. The following is likely unsafe...\nnumeric_to_blitz_type_mapping[type(1L)] = 'int'\n\nclass scalar_specification(base_specification):\n _build_information = [scalar_info.scalar_info()] \n\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name\n new_spec.numeric_type = type(value)\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n if self.compiler == 'msvc':\n return self.msvc_decl_code(templatize,inline)\n else:\n return self.template_decl_code(templatize,inline) \n\n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_scalar<%(type)s >(%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n ValueError, 'msvc compiler does not support templated scalar code.'\\\n 'try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n\n #def c_function_declaration_code(self):\n # code = '%s &%s\" % \\\n # (numeric_to_blitz_type_mapping[self.numeric_type], self.name)\n # return code\n\n def __repr__(self):\n msg = \"(%s:: name: %s, type: %s)\" % \\\n (self.type_name,self.name, self.numeric_type)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.__class__, other.__class__)\n\nclass int_specification(scalar_specification):\n type_name = 'int'\n def type_match(self,value):\n return type(value) in [IntType, LongType]\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Int(%s);\\n' % (self.name,self.name) \n return code\n \nclass float_specification(scalar_specification):\n type_name = 'float'\n def type_match(self,value):\n return type(value) in [FloatType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Float(%s);\\n' % (self.name,self.name) \n return code\n\nclass complex_specification(scalar_specification):\n type_name = 'complex'\n def type_match(self,value):\n return type(value) in [ComplexType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Complex(%s.real(),%s.imag());\\n' % \\\n (self.name,self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n ", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [ "self", "name", "value" ], "start_line": 35, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "template_decl_code", "long_name": "template_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 8, "complexity": 1, "token_count": 48, "parameters": [ "self", "template", "inline" ], "start_line": 49, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 13, "complexity": 2, "token_count": 63, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 71, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 14, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 78, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 3, "token_count": 42, "parameters": [ "self", "other" ], "start_line": 82, "end_line": 86, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 18, "parameters": [ "self", "value" ], "start_line": 90, "end_line": 91, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 93, "end_line": 95, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 99, "end_line": 100, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 101, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 107, "end_line": 108, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 109, "end_line": 112, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 114, "end_line": 116, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 118, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [ "self", "name", "value" ], "start_line": 35, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 2, "token_count": 40, "parameters": [ "self", "templatize", "inline" ], "start_line": 42, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "template_decl_code", "long_name": "template_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 8, "complexity": 1, "token_count": 48, "parameters": [ "self", "template", "inline" ], "start_line": 48, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 12, "complexity": 2, "token_count": 61, "parameters": [ "self", "template", "inline" ], "start_line": 57, "end_line": 69, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 76, "end_line": 79, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 3, "token_count": 42, "parameters": [ "self", "other" ], "start_line": 80, "end_line": 84, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 18, "parameters": [ "self", "value" ], "start_line": 88, "end_line": 89, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 91, "end_line": 93, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 97, "end_line": 98, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 99, "end_line": 101, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 105, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 107, "end_line": 110, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 112, "end_line": 114, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 116, "end_line": 118, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 13, "complexity": 2, "token_count": 63, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 71, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 14, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 2, "token_count": 40, "parameters": [ "self", "templatize", "inline" ], "start_line": 42, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 } ], "nloc": 83, "complexity": 16, "token_count": 538, "diff_parsed": { "added": [ " #if self.compiler == 'msvc':", " # return self.msvc_decl_code(templatize,inline)", " #else:", " # return self.template_decl_code(templatize,inline) \\", " return self.msvc_decl_code(templatize,inline)", " template = 'scalar_handler x__; \\n' \\", " '%(type)s %(name)s = '\\", " 'x__convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'" ], "deleted": [ " if self.compiler == 'msvc':", " return self.msvc_decl_code(templatize,inline)", " else:", " return self.template_decl_code(templatize,inline)", " template = '%(type)s %(name)s = '\\", " 'convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'" ] } } ] }, { "hash": "18eb840d1ff968459c64a73a2131cc50be67c7cb", "msg": "further changes to make class versions of converters work", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T04:44:28+00:00", "author_timezone": 0, "committer_date": "2002-01-17T04:44:28+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "1ed96f36cb3ecfceb682a9a96d3513ed5189a409" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 12, "insertions": 31, "lines": 43, "files": 5, "dmm_unit_size": 1.0, "dmm_unit_complexity": 0.0, "dmm_unit_interfacing": 1.0, "modified_files": [ { "old_path": "weave/common_spec.py", "new_path": "weave/common_spec.py", "filename": "common_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -30,9 +30,8 @@ def declaration_code(self,templatize = 0,inline=0):\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n- 'file_converter x__;\\n \\\n 'PyObject* py_%s = %s;\\n' \\\n- 'FILE* %s = x__.convert_to_file(py_%s,\"%s\");\\n' % \\\n+ 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n@@ -51,8 +50,7 @@ def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n- code = 'callable_converter x__;\\n \\\n- 'PyObject* %s = x__.convert_to_callable(%s,\"%s\");\\n' % \\\n+ code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n \n", "added_lines": 2, "deleted_lines": 4, "source_code": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'file_converter x__;\\n \\\n 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'callable_converter x__;\\n \\\n 'PyObject* %s = x__.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 7, "complexity": 1, "token_count": 51, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 36, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 37, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 23, "parameters": [ "self", "value" ], "start_line": 45, "end_line": 47, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 49, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 57, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 28, "complexity": 1, "token_count": 97, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 59, "end_line": 61, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 63, "end_line": 65, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 7, "complexity": 1, "token_count": 51, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 36, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 } ], "nloc": 46, "complexity": 11, "token_count": 303, "diff_parsed": { "added": [ " 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\", " code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\" ], "deleted": [ " 'file_converter x__;\\n \\", " 'FILE* %s = x__.convert_to_file(py_%s,\"%s\");\\n' % \\", " code = 'callable_converter x__;\\n \\", " 'PyObject* %s = x__.convert_to_callable(%s,\"%s\");\\n' % \\" ] } }, { "old_path": "weave/conversion_code.py", "new_path": "weave/conversion_code.py", "filename": "conversion_code.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -102,6 +102,8 @@ class file_handler\n }\n };\n \n+file_handler x__file_handler = file_handler();\n+\n PyObject* file_to_py(FILE* file, char* name, char* mode)\n {\n PyObject* py_obj = NULL;\n@@ -145,6 +147,8 @@ class instance_handler\n }\n };\n \n+instance_handler x__instance_handler = instance_handler();\n+\n PyObject* instance_to_py(PyObject* instance)\n {\n // Don't think I need to do anything...\n@@ -186,6 +190,8 @@ class callable_handler\n }\n };\n \n+callable_handler x__callable_handler = callable_handler();\n+\n PyObject* callable_to_py(PyObject* callable)\n {\n // Don't think I need to do anything...\n@@ -226,6 +232,8 @@ class module_handler\n }\n };\n \n+module_handler x__module_handler = module_handler();\n+\n PyObject* module_to_py(PyObject* module)\n {\n // Don't think I need to do anything...\n@@ -399,6 +407,7 @@ class scalar_handler\n }\n };\n \n+scalar_handler x__scalar_handler = scalar_handler();\n /////////////////////////////////////\n // The following functions are used for scalar conversions in msvc\n // because it doesn't handle templates as well.\n", "added_lines": 9, "deleted_lines": 0, "source_code": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nclass file_handler\n{\npublic:\n FILE* convert_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n \n FILE* py_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n};\n\nfile_handler x__file_handler = file_handler();\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nclass instance_handler\n{\npublic:\n PyObject* convert_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\ninstance_handler x__instance_handler = instance_handler();\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nclass callable_handler\n{\npublic: \n PyObject* convert_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\ncallable_handler x__callable_handler = callable_handler();\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nclass module_handler\n{\npublic:\n PyObject* convert_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nmodule_handler x__module_handler = module_handler();\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nclass scalar_handler\n{\npublic: \n int convert_to_int(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n }\n long convert_to_long(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n }\n\n double convert_to_float(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n }\n\n// complex not checked.\n std::complex convert_to_complex(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n }\n};\n\nscalar_handler x__scalar_handler = scalar_handler();\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "source_code_before": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nclass file_handler\n{\npublic:\n FILE* convert_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n \n FILE* py_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n};\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nclass instance_handler\n{\npublic:\n PyObject* convert_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nclass callable_handler\n{\npublic: \n PyObject* convert_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nclass module_handler\n{\npublic:\n PyObject* convert_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nclass scalar_handler\n{\npublic: \n int convert_to_int(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n }\n long convert_to_long(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n }\n\n double convert_to_float(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n }\n\n// complex not checked.\n std::complex convert_to_complex(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n }\n};\n\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 409, "complexity": 0, "token_count": 33, "diff_parsed": { "added": [ "file_handler x__file_handler = file_handler();", "", "instance_handler x__instance_handler = instance_handler();", "", "callable_handler x__callable_handler = callable_handler();", "", "module_handler x__module_handler = module_handler();", "", "scalar_handler x__scalar_handler = scalar_handler();" ], "deleted": [] } }, { "old_path": "weave/cxx_info.py", "new_path": "weave/cxx_info.py", "filename": "cxx_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -4,6 +4,7 @@\n \"\"\"\n class string_handler\n {\n+public:\n static Py::String convert_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n@@ -11,6 +12,9 @@ class string_handler\n return Py::String(py_obj);\n }\n };\n+\n+string_handler x__string_handler = string_handler();\n+\n static Py::String py_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n@@ -25,6 +29,7 @@ class string_handler\n \n class list_handler\n {\n+public:\n Py::List convert_to_list(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n@@ -33,6 +38,8 @@ class list_handler\n }\n };\n \n+list_handler x__list_handler = list_handler();\n+\n static Py::List py_to_list(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n@@ -45,13 +52,16 @@ class list_handler\n \"\"\"\n class dict_handler\n {\n+public:\n Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n-}\n+};\n+\n+dict_handler x__dict_handler = dict_handler();\n \n static Py::Dict py_to_dict(PyObject* py_obj,char* name)\n {\n@@ -65,6 +75,7 @@ class dict_handler\n \"\"\"\n class tuple_handler\n {\n+public:\n Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n@@ -73,6 +84,8 @@ class tuple_handler\n }\n };\n \n+tuple_handler x__tuple_handler = tuple_handler();\n+\n static Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n", "added_lines": 14, "deleted_lines": 1, "source_code": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\npublic:\n static Py::String convert_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\n\nstring_handler x__string_handler = string_handler();\n\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\npublic:\n Py::List convert_to_list(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nlist_handler x__list_handler = list_handler();\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\npublic:\n Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n};\n\ndict_handler x__dict_handler = dict_handler();\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\npublic:\n Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\ntuple_handler x__tuple_handler = tuple_handler();\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "source_code_before": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\n static Py::String convert_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\n Py::List convert_to_list(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\n Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n}\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\n Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 103, "complexity": 0, "token_count": 137, "diff_parsed": { "added": [ "public:", "", "string_handler x__string_handler = string_handler();", "", "public:", "list_handler x__list_handler = list_handler();", "", "public:", "};", "", "dict_handler x__dict_handler = dict_handler();", "public:", "tuple_handler x__tuple_handler = tuple_handler();", "" ], "deleted": [ "}" ] } }, { "old_path": "weave/scalar_spec.py", "new_path": "weave/scalar_spec.py", "filename": "scalar_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -64,9 +64,8 @@ def msvc_decl_code(self,template = 0,inline=0):\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n- template = 'scalar_handler x__; \\n' \\\n- '%(type)s %(name)s = '\\\n- 'x__convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n+ template = '%(type)s %(name)s = '\\\n+ 'x__scalar_handler.convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n", "added_lines": 2, "deleted_lines": 3, "source_code": "from base_spec import base_specification\nimport scalar_info\n#from Numeric import *\nfrom types import *\n\n# the following typemaps are for 32 bit platforms. A way to do this\n# general case? maybe ask numeric types how long they are and base\n# the decisions on that.\n\nnumeric_to_blitz_type_mapping = {}\n\nnumeric_to_blitz_type_mapping['T'] = 'T' # for templates\nnumeric_to_blitz_type_mapping['F'] = 'std::complex '\nnumeric_to_blitz_type_mapping['D'] = 'std::complex '\nnumeric_to_blitz_type_mapping['f'] = 'float'\nnumeric_to_blitz_type_mapping['d'] = 'double'\nnumeric_to_blitz_type_mapping['1'] = 'char'\nnumeric_to_blitz_type_mapping['b'] = 'unsigned char'\nnumeric_to_blitz_type_mapping['s'] = 'short'\nnumeric_to_blitz_type_mapping['i'] = 'int'\n# not strictly correct, but shoulld be fine fo numeric work.\n# add test somewhere to make sure long can be cast to int before using.\nnumeric_to_blitz_type_mapping['l'] = 'int'\n\n# standard Python numeric type mappings.\nnumeric_to_blitz_type_mapping[type(1)] = 'int'\nnumeric_to_blitz_type_mapping[type(1.)] = 'double'\nnumeric_to_blitz_type_mapping[type(1.+1.j)] = 'std::complex '\n#hmmm. The following is likely unsafe...\nnumeric_to_blitz_type_mapping[type(1L)] = 'int'\n\nclass scalar_specification(base_specification):\n _build_information = [scalar_info.scalar_info()] \n\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name\n new_spec.numeric_type = type(value)\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n #if self.compiler == 'msvc':\n # return self.msvc_decl_code(templatize,inline)\n #else:\n # return self.template_decl_code(templatize,inline) \\\n return self.msvc_decl_code(templatize,inline)\n\n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_scalar<%(type)s >(%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n ValueError, 'msvc compiler does not support templated scalar code.'\\\n 'try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'x__scalar_handler.convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n\n #def c_function_declaration_code(self):\n # code = '%s &%s\" % \\\n # (numeric_to_blitz_type_mapping[self.numeric_type], self.name)\n # return code\n\n def __repr__(self):\n msg = \"(%s:: name: %s, type: %s)\" % \\\n (self.type_name,self.name, self.numeric_type)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.__class__, other.__class__)\n\nclass int_specification(scalar_specification):\n type_name = 'int'\n def type_match(self,value):\n return type(value) in [IntType, LongType]\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Int(%s);\\n' % (self.name,self.name) \n return code\n \nclass float_specification(scalar_specification):\n type_name = 'float'\n def type_match(self,value):\n return type(value) in [FloatType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Float(%s);\\n' % (self.name,self.name) \n return code\n\nclass complex_specification(scalar_specification):\n type_name = 'complex'\n def type_match(self,value):\n return type(value) in [ComplexType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Complex(%s.real(),%s.imag());\\n' % \\\n (self.name,self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n ", "source_code_before": "from base_spec import base_specification\nimport scalar_info\n#from Numeric import *\nfrom types import *\n\n# the following typemaps are for 32 bit platforms. A way to do this\n# general case? maybe ask numeric types how long they are and base\n# the decisions on that.\n\nnumeric_to_blitz_type_mapping = {}\n\nnumeric_to_blitz_type_mapping['T'] = 'T' # for templates\nnumeric_to_blitz_type_mapping['F'] = 'std::complex '\nnumeric_to_blitz_type_mapping['D'] = 'std::complex '\nnumeric_to_blitz_type_mapping['f'] = 'float'\nnumeric_to_blitz_type_mapping['d'] = 'double'\nnumeric_to_blitz_type_mapping['1'] = 'char'\nnumeric_to_blitz_type_mapping['b'] = 'unsigned char'\nnumeric_to_blitz_type_mapping['s'] = 'short'\nnumeric_to_blitz_type_mapping['i'] = 'int'\n# not strictly correct, but shoulld be fine fo numeric work.\n# add test somewhere to make sure long can be cast to int before using.\nnumeric_to_blitz_type_mapping['l'] = 'int'\n\n# standard Python numeric type mappings.\nnumeric_to_blitz_type_mapping[type(1)] = 'int'\nnumeric_to_blitz_type_mapping[type(1.)] = 'double'\nnumeric_to_blitz_type_mapping[type(1.+1.j)] = 'std::complex '\n#hmmm. The following is likely unsafe...\nnumeric_to_blitz_type_mapping[type(1L)] = 'int'\n\nclass scalar_specification(base_specification):\n _build_information = [scalar_info.scalar_info()] \n\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name\n new_spec.numeric_type = type(value)\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n #if self.compiler == 'msvc':\n # return self.msvc_decl_code(templatize,inline)\n #else:\n # return self.template_decl_code(templatize,inline) \\\n return self.msvc_decl_code(templatize,inline)\n\n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_scalar<%(type)s >(%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n ValueError, 'msvc compiler does not support templated scalar code.'\\\n 'try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = 'scalar_handler x__; \\n' \\\n '%(type)s %(name)s = '\\\n 'x__convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n\n #def c_function_declaration_code(self):\n # code = '%s &%s\" % \\\n # (numeric_to_blitz_type_mapping[self.numeric_type], self.name)\n # return code\n\n def __repr__(self):\n msg = \"(%s:: name: %s, type: %s)\" % \\\n (self.type_name,self.name, self.numeric_type)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.__class__, other.__class__)\n\nclass int_specification(scalar_specification):\n type_name = 'int'\n def type_match(self,value):\n return type(value) in [IntType, LongType]\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Int(%s);\\n' % (self.name,self.name) \n return code\n \nclass float_specification(scalar_specification):\n type_name = 'float'\n def type_match(self,value):\n return type(value) in [FloatType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Float(%s);\\n' % (self.name,self.name) \n return code\n\nclass complex_specification(scalar_specification):\n type_name = 'complex'\n def type_match(self,value):\n return type(value) in [ComplexType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Complex(%s.real(),%s.imag());\\n' % \\\n (self.name,self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n ", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [ "self", "name", "value" ], "start_line": 35, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "template_decl_code", "long_name": "template_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 8, "complexity": 1, "token_count": 48, "parameters": [ "self", "template", "inline" ], "start_line": 49, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 12, "complexity": 2, "token_count": 61, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 77, "end_line": 80, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 3, "token_count": 42, "parameters": [ "self", "other" ], "start_line": 81, "end_line": 85, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 18, "parameters": [ "self", "value" ], "start_line": 89, "end_line": 90, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 92, "end_line": 94, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 98, "end_line": 99, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 100, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 106, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 108, "end_line": 111, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 113, "end_line": 115, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 117, "end_line": 119, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [ "self", "name", "value" ], "start_line": 35, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "template_decl_code", "long_name": "template_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 8, "complexity": 1, "token_count": 48, "parameters": [ "self", "template", "inline" ], "start_line": 49, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 13, "complexity": 2, "token_count": 63, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 71, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 14, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 78, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 3, "token_count": 42, "parameters": [ "self", "other" ], "start_line": 82, "end_line": 86, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 18, "parameters": [ "self", "value" ], "start_line": 90, "end_line": 91, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 93, "end_line": 95, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 99, "end_line": 100, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 101, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 107, "end_line": 108, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 109, "end_line": 112, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 114, "end_line": 116, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 118, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 12, "complexity": 2, "token_count": 61, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 } ], "nloc": 82, "complexity": 16, "token_count": 536, "diff_parsed": { "added": [ " template = '%(type)s %(name)s = '\\", " 'x__scalar_handler.convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'" ], "deleted": [ " template = 'scalar_handler x__; \\n' \\", " '%(type)s %(name)s = '\\", " 'x__convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'" ] } }, { "old_path": "weave/sequence_spec.py", "new_path": "weave/sequence_spec.py", "filename": "sequence_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -25,7 +25,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\\n+ code = 'Py::String %s = x__string_handler.convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n@@ -40,7 +40,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\\n+ code = 'Py::List %s = x__list_handler.convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n@@ -54,7 +54,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::Dict %s = convert_to_dict(%s,\"%s\");\\n' % \\\n+ code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n@@ -69,7 +69,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\\n+ code = 'Py::Tuple %s = x__tuple_handler.convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n", "added_lines": 4, "deleted_lines": 4, "source_code": "import cxx_info\nfrom base_spec import base_specification\nfrom types import *\nimport os\n\nclass base_cxx_specification(base_specification):\n _build_information = [cxx_info.cxx_info()]\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(%s:: name: %s)\" % (self.type_name,self.name)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \nclass string_specification(base_cxx_specification):\n type_name = 'string'\n def type_match(self,value):\n return type(value) in [StringType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::String %s = x__string_handler.convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\n\nclass list_specification(base_cxx_specification):\n type_name = 'list'\n def type_match(self,value):\n return type(value) in [ListType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::List %s = x__list_handler.convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass dict_specification(base_cxx_specification):\n type_name = 'dict'\n def type_match(self,value):\n return type(value) in [DictType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass tuple_specification(base_cxx_specification):\n type_name = 'tuple'\n def type_match(self,value):\n return type(value) in [TupleType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Tuple %s = x__tuple_handler.convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n", "source_code_before": "import cxx_info\nfrom base_spec import base_specification\nfrom types import *\nimport os\n\nclass base_cxx_specification(base_specification):\n _build_information = [cxx_info.cxx_info()]\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(%s:: name: %s)\" % (self.type_name,self.name)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \nclass string_specification(base_cxx_specification):\n type_name = 'string'\n def type_match(self,value):\n return type(value) in [StringType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\n\nclass list_specification(base_cxx_specification):\n type_name = 'list'\n def type_match(self,value):\n return type(value) in [ListType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass dict_specification(base_cxx_specification):\n type_name = 'dict'\n def type_match(self,value):\n return type(value) in [DictType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Dict %s = convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass tuple_specification(base_cxx_specification):\n type_name = 'tuple'\n def type_match(self,value):\n return type(value) in [TupleType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "sequence_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 8, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 16, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 23, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 38, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 41, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 46, "end_line": 48, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 52, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 67, "end_line": 68, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 70, "end_line": 74, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 75, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "sequence_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 8, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 16, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 23, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 38, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 41, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 46, "end_line": 48, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 52, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 67, "end_line": 68, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 70, "end_line": 74, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 75, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 } ], "changed_methods": [ { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 } ], "nloc": 64, "complexity": 16, "token_count": 451, "diff_parsed": { "added": [ " code = 'Py::String %s = x__string_handler.convert_to_string(%s,\"%s\");\\n' % \\", " code = 'Py::List %s = x__list_handler.convert_to_list(%s,\"%s\");\\n' % \\", " code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\", " code = 'Py::Tuple %s = x__tuple_handler.convert_to_tuple(%s,\"%s\");\\n' % \\" ], "deleted": [ " code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\", " code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\", " code = 'Py::Dict %s = convert_to_dict(%s,\"%s\");\\n' % \\", " code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\" ] } } ] }, { "hash": "d7f048bc01cf4d21cc4b167bb29bc23a8bc2c8a5", "msg": "fixing a few typos", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T04:55:19+00:00", "author_timezone": 0, "committer_date": "2002-01-17T04:55:19+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "18eb840d1ff968459c64a73a2131cc50be67c7cb" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 0, "lines": 1, "files": 1, "dmm_unit_size": 0.0, "dmm_unit_complexity": 0.0, "dmm_unit_interfacing": 1.0, "modified_files": [ { "old_path": "weave/common_spec.py", "new_path": "weave/common_spec.py", "filename": "common_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -30,7 +30,6 @@ def declaration_code(self,templatize = 0,inline=0):\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n- 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n", "added_lines": 0, "deleted_lines": 1, "source_code": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 6, "complexity": 1, "token_count": 49, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 35, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 36, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 23, "parameters": [ "self", "value" ], "start_line": 44, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 48, "end_line": 54, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 56, "end_line": 58, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 60, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 7, "complexity": 1, "token_count": 51, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 36, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 37, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 23, "parameters": [ "self", "value" ], "start_line": 45, "end_line": 47, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 49, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 57, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 7, "complexity": 1, "token_count": 51, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 36, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 } ], "nloc": 45, "complexity": 11, "token_count": 301, "diff_parsed": { "added": [], "deleted": [ " 'PyObject* py_%s = %s;\\n' \\" ] } } ] }, { "hash": "0c8b48993f0556810bc18449854f00d1938f60d3", "msg": "changed converter class method calls to be handled through macros. This will require less code when we switch back to functional conversion methods. It also cleans up the compiled_func generated a little.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T18:28:41+00:00", "author_timezone": 0, "committer_date": "2002-01-17T18:28:41+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "d7f048bc01cf4d21cc4b167bb29bc23a8bc2c8a5" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 134, "insertions": 153, "lines": 287, "files": 6, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/blitz_info.py", "new_path": "weave/blitz_info.py", "filename": "blitz_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -36,7 +36,7 @@ class py_type >{public: enum { code = PyArray_CFLOAT};};\n class py_type >{public: enum { code = PyArray_CDOUBLE};};\n \n template\n-static blitz::Array convert_to_blitz(PyObject* py_obj,char* name)\n+static blitz::Array convert_to_blitz(PyObject* py_obj,const char* name)\n {\n \n PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n@@ -58,7 +58,7 @@ class py_type >{public: enum { code = PyArray_CDOUBLE};};\n }\n \n template\n-static blitz::Array py_to_blitz(PyObject* py_obj,char* name)\n+static blitz::Array py_to_blitz(PyObject* py_obj,const char* name)\n {\n \n PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n", "added_lines": 2, "deleted_lines": 2, "source_code": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyObject* py_obj,const char* name)\n{\n\n PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n conversion_numpy_check_size(arr_obj,N,name);\n conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyObject* py_obj,const char* name)\n{\n\n PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n numpy_check_size(arr_obj,N,name);\n numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "source_code_before": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyObject* py_obj,char* name)\n{\n\n PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n conversion_numpy_check_size(arr_obj,N,name);\n conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyObject* py_obj,char* name)\n{\n\n PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n numpy_check_size(arr_obj,N,name);\n numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "methods": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 101, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "methods_before": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 101, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "changed_methods": [], "nloc": 97, "complexity": 2, "token_count": 120, "diff_parsed": { "added": [ "static blitz::Array convert_to_blitz(PyObject* py_obj,const char* name)", "static blitz::Array py_to_blitz(PyObject* py_obj,const char* name)" ], "deleted": [ "static blitz::Array convert_to_blitz(PyObject* py_obj,char* name)", "static blitz::Array py_to_blitz(PyObject* py_obj,char* name)" ] } }, { "old_path": "weave/common_spec.py", "new_path": "weave/common_spec.py", "filename": "common_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -30,7 +30,7 @@ def declaration_code(self,templatize = 0,inline=0):\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n- 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n+ 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n@@ -49,7 +49,7 @@ def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n- code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\\n+ code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n \n", "added_lines": 2, "deleted_lines": 2, "source_code": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "from base_spec import base_specification\nimport common_info\nfrom types import *\nimport os\n\nclass common_base_specification(base_specification):\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(file:: name: %s)\" % self.name\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \n \nclass file_specification(common_base_specification):\n type_name = 'file'\n _build_information = [common_info.file_info()]\n def type_match(self,value):\n return type(value) in [FileType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* py_%s = %s;\\n' \\\n # 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name,self.name,self.name)\n code = 'PyObject* py_%s = %s;\\n' \\\n 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name,self.name,self.name)\n return code \n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\nclass callable_specification(common_base_specification):\n type_name = 'callable'\n _build_information = [common_info.callable_info()]\n def type_match(self,value):\n # probably should test for callable classes here also.\n return type(value) in [FunctionType,MethodType,type(len)]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n #code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\\n # (self.name,var_name,self.name)\n code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 6, "complexity": 1, "token_count": 49, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 35, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 36, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 23, "parameters": [ "self", "value" ], "start_line": 44, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 48, "end_line": 54, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 56, "end_line": 58, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 60, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "common_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 7, "end_line": 11, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 12, "end_line": 14, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "common_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 15, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 24, "end_line": 25, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 6, "complexity": 1, "token_count": 49, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 35, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 36, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "common_spec.py", "nloc": 2, "complexity": 1, "token_count": 23, "parameters": [ "self", "value" ], "start_line": 44, "end_line": 46, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 48, "end_line": 54, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 56, "end_line": 58, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "common_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 60, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "common_spec.py", "nloc": 6, "complexity": 1, "token_count": 49, "parameters": [ "self", "templatize", "inline" ], "start_line": 27, "end_line": 35, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 } ], "nloc": 45, "complexity": 11, "token_count": 301, "diff_parsed": { "added": [ " 'FILE* %s = convert_to_file(py_%s,\"%s\");\\n' % \\", " code = 'PyObject* %s = convert_to_callable(%s,\"%s\");\\n' % \\" ], "deleted": [ " 'FILE* %s = x__file_converter.convert_to_file(py_%s,\"%s\");\\n' % \\", " code = 'PyObject* %s = x__callable_handler.convert_to_callable(%s,\"%s\");\\n' % \\" ] } }, { "old_path": "weave/conversion_code.py", "new_path": "weave/conversion_code.py", "filename": "conversion_code.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -53,7 +53,7 @@\n throw 1;\n }\n \n-void handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n+void handle_bad_type(PyObject* py_obj, const char* good_type, const char* var_name)\n {\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n@@ -61,7 +61,7 @@\n throw_error(PyExc_TypeError,msg); \n }\n \n-void handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n+void handle_conversion_error(PyObject* py_obj, const char* good_type, const char* var_name)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n@@ -81,7 +81,7 @@\n class file_handler\n {\n public:\n- FILE* convert_to_file(PyObject* py_obj, char* name)\n+ FILE* convert_to_file(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n@@ -91,7 +91,7 @@ class file_handler\n return PyFile_AsFile(py_obj);\n }\n \n- FILE* py_to_file(PyObject* py_obj, char* name)\n+ FILE* py_to_file(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n@@ -103,6 +103,8 @@ class file_handler\n };\n \n file_handler x__file_handler = file_handler();\n+#define convert_to_file(py_obj,name) x__file_handler.convert_to_file(py_obj,name)\n+#define py_to_file(py_obj,name) x__file_handler.py_to_file(py_obj,name)\n \n PyObject* file_to_py(FILE* file, char* name, char* mode)\n {\n@@ -124,7 +126,7 @@ class file_handler\n class instance_handler\n {\n public:\n- PyObject* convert_to_instance(PyObject* py_obj, char* name)\n+ PyObject* convert_to_instance(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n@@ -135,7 +137,7 @@ class instance_handler\n return py_obj;\n }\n \n- PyObject* py_to_instance(PyObject* py_obj, char* name)\n+ PyObject* py_to_instance(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n@@ -148,6 +150,8 @@ class instance_handler\n };\n \n instance_handler x__instance_handler = instance_handler();\n+#define convert_to_instance(py_obj,name) x__instance_handler.convert_to_instance(py_obj,name)\n+#define py_to_instance(py_obj,name) x__instance_handler.py_to_instance(py_obj,name)\n \n PyObject* instance_to_py(PyObject* instance)\n {\n@@ -167,7 +171,7 @@ class instance_handler\n class callable_handler\n {\n public: \n- PyObject* convert_to_callable(PyObject* py_obj, char* name)\n+ PyObject* convert_to_callable(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n@@ -178,7 +182,7 @@ class callable_handler\n return py_obj;\n }\n \n- PyObject* py_to_callable(PyObject* py_obj, char* name)\n+ PyObject* py_to_callable(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n@@ -191,6 +195,8 @@ class callable_handler\n };\n \n callable_handler x__callable_handler = callable_handler();\n+#define convert_to_callable(py_obj,name) x__callable_handler.convert_to_callable(py_obj,name)\n+#define py_to_callable(py_obj,name) x__callable_handler.py_to_callable(py_obj,name)\n \n PyObject* callable_to_py(PyObject* callable)\n {\n@@ -209,7 +215,7 @@ class callable_handler\n class module_handler\n {\n public:\n- PyObject* convert_to_module(PyObject* py_obj, char* name)\n+ PyObject* convert_to_module(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n@@ -220,7 +226,7 @@ class module_handler\n return py_obj;\n }\n \n- PyObject* py_to_module(PyObject* py_obj, char* name)\n+ PyObject* py_to_module(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n@@ -233,6 +239,8 @@ class module_handler\n };\n \n module_handler x__module_handler = module_handler();\n+#define convert_to_module(py_obj,name) x__module_handler.convert_to_module(py_obj,name)\n+#define py_to_module(py_obj,name) x__module_handler.py_to_module(py_obj,name)\n \n PyObject* module_to_py(PyObject* module)\n {\n@@ -246,21 +254,102 @@ class module_handler\n # Scalar conversion code\n #############################################################\n \n-import base_info\n+# These non-templated version is now used for most scalar conversions.\n+non_template_scalar_support_code = \\\n+\"\"\"\n+\n+class scalar_handler\n+{\n+public: \n+ int convert_to_int(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_conversion_error(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+ }\n+ long convert_to_long(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_conversion_error(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+ }\n+\n+ double convert_to_float(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_conversion_error(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+ }\n+\n+ std::complex convert_to_complex(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_conversion_error(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+ }\n+\n+ int py_to_int(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyInt_Check(py_obj))\n+ handle_bad_type(py_obj,\"int\", name);\n+ return (int) PyInt_AsLong(py_obj);\n+ }\n+ \n+ long py_to_long(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyLong_Check(py_obj))\n+ handle_bad_type(py_obj,\"long\", name);\n+ return (long) PyLong_AsLong(py_obj);\n+ }\n+ \n+ double py_to_float(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyFloat_Check(py_obj))\n+ handle_bad_type(py_obj,\"float\", name);\n+ return PyFloat_AsDouble(py_obj);\n+ }\n+ \n+ std::complex py_to_complex(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyComplex_Check(py_obj))\n+ handle_bad_type(py_obj,\"complex\", name);\n+ return std::complex(PyComplex_RealAsDouble(py_obj),\n+ PyComplex_ImagAsDouble(py_obj)); \n+ }\n+\n+};\n+\n+scalar_handler x__scalar_handler = scalar_handler();\n+#define convert_to_int(py_obj,name) x__scalar_handler.convert_to_int(py_obj,name)\n+#define py_to_int(py_obj,name) x__scalar_handler.py_to_int(py_obj,name)\n+\n+#define convert_to_long(py_obj,name) x__scalar_handler.convert_to_long(py_obj,name)\n+#define py_to_long(py_obj,name) x__scalar_handler.py_to_long(py_obj,name)\n+\n+#define convert_to_float(py_obj,name) x__scalar_handler.convert_to_float(py_obj,name)\n+#define py_to_float(py_obj,name) x__scalar_handler.py_to_float(py_obj,name)\n+\n+#define convert_to_complex(py_obj,name) x__scalar_handler.convert_to_complex(py_obj,name)\n+#define py_to_complex(py_obj,name) x__scalar_handler.py_to_complex(py_obj,name)\n+\n+\"\"\" \n \n # this code will not build with msvc...\n+# This is only used for blitz stuff now. The non-templated\n+# version, defined further down, is now used for most code.\n scalar_support_code = \\\n \"\"\"\n // conversion routines\n \n template \n-static T convert_to_scalar(PyObject* py_obj,char* name)\n+static T convert_to_scalar(PyObject* py_obj,const char* name)\n {\n //never used.\n return (T) 0;\n }\n template<>\n-static int convert_to_scalar(PyObject* py_obj,char* name)\n+static int convert_to_scalar(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n@@ -268,7 +357,7 @@ class module_handler\n }\n \n template<>\n-static long convert_to_scalar(PyObject* py_obj,char* name)\n+static long convert_to_scalar(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n@@ -276,7 +365,7 @@ class module_handler\n }\n \n template<> \n-static double convert_to_scalar(PyObject* py_obj,char* name)\n+static double convert_to_scalar(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n@@ -284,7 +373,7 @@ class module_handler\n }\n \n template<> \n-static float convert_to_scalar(PyObject* py_obj,char* name)\n+static float convert_to_scalar(PyObject* py_obj,const char* name)\n {\n return (float) convert_to_scalar(py_obj,name);\n }\n@@ -292,7 +381,7 @@ class module_handler\n // complex not checked.\n template<> \n static std::complex convert_to_scalar >(PyObject* py_obj,\n- char* name)\n+ const char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n@@ -301,7 +390,7 @@ class module_handler\n }\n template<> \n static std::complex convert_to_scalar >(\n- PyObject* py_obj,char* name)\n+ PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n@@ -313,13 +402,13 @@ class module_handler\n // standard translation routines\n \n template \n-static T py_to_scalar(PyObject* py_obj,char* name)\n+static T py_to_scalar(PyObject* py_obj,const char* name)\n {\n //never used.\n return (T) 0;\n }\n template<>\n-static int py_to_scalar(PyObject* py_obj,char* name)\n+static int py_to_scalar(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n@@ -327,7 +416,7 @@ class module_handler\n }\n \n template<>\n-static long py_to_scalar(PyObject* py_obj,char* name)\n+static long py_to_scalar(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n@@ -335,7 +424,7 @@ class module_handler\n }\n \n template<> \n-static double py_to_scalar(PyObject* py_obj,char* name)\n+static double py_to_scalar(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n@@ -343,7 +432,7 @@ class module_handler\n }\n \n template<> \n-static float py_to_scalar(PyObject* py_obj,char* name)\n+static float py_to_scalar(PyObject* py_obj,const char* name)\n {\n return (float) py_to_scalar(py_obj,name);\n }\n@@ -351,7 +440,7 @@ class module_handler\n // complex not checked.\n template<> \n static std::complex py_to_scalar >(PyObject* py_obj,\n- char* name)\n+ const char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n@@ -360,81 +449,7 @@ class module_handler\n }\n template<> \n static std::complex py_to_scalar >(\n- PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyComplex_Check(py_obj))\n- handle_bad_type(py_obj,\"complex\", name);\n- return std::complex(PyComplex_RealAsDouble(py_obj),\n- PyComplex_ImagAsDouble(py_obj)); \n-}\n-\"\"\" \n-\n-non_template_scalar_support_code = \\\n-\"\"\"\n-\n-// Conversion Errors\n-\n-class scalar_handler\n-{\n-public: \n- int convert_to_int(PyObject* py_obj,char* name)\n- {\n- if (!py_obj || !PyInt_Check(py_obj))\n- handle_conversion_error(py_obj,\"int\", name);\n- return (int) PyInt_AsLong(py_obj);\n- }\n- long convert_to_long(PyObject* py_obj,char* name)\n- {\n- if (!py_obj || !PyLong_Check(py_obj))\n- handle_conversion_error(py_obj,\"long\", name);\n- return (long) PyLong_AsLong(py_obj);\n- }\n-\n- double convert_to_float(PyObject* py_obj,char* name)\n- {\n- if (!py_obj || !PyFloat_Check(py_obj))\n- handle_conversion_error(py_obj,\"float\", name);\n- return PyFloat_AsDouble(py_obj);\n- }\n-\n-// complex not checked.\n- std::complex convert_to_complex(PyObject* py_obj,char* name)\n- {\n- if (!py_obj || !PyComplex_Check(py_obj))\n- handle_conversion_error(py_obj,\"complex\", name);\n- return std::complex(PyComplex_RealAsDouble(py_obj),\n- PyComplex_ImagAsDouble(py_obj)); \n- }\n-};\n-\n-scalar_handler x__scalar_handler = scalar_handler();\n-/////////////////////////////////////\n-// The following functions are used for scalar conversions in msvc\n-// because it doesn't handle templates as well.\n-\n-static int py_to_int(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyInt_Check(py_obj))\n- handle_bad_type(py_obj,\"int\", name);\n- return (int) PyInt_AsLong(py_obj);\n-}\n-\n-static long py_to_long(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyLong_Check(py_obj))\n- handle_bad_type(py_obj,\"long\", name);\n- return (long) PyLong_AsLong(py_obj);\n-}\n-\n-static double py_to_float(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyFloat_Check(py_obj))\n- handle_bad_type(py_obj,\"float\", name);\n- return PyFloat_AsDouble(py_obj);\n-}\n-\n-// complex not checked.\n-static std::complex py_to_complex(PyObject* py_obj,char* name)\n+ PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n", "added_lines": 114, "deleted_lines": 99, "source_code": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, const char* good_type, const char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, const char* good_type, const char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nclass file_handler\n{\npublic:\n FILE* convert_to_file(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n \n FILE* py_to_file(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n};\n\nfile_handler x__file_handler = file_handler();\n#define convert_to_file(py_obj,name) x__file_handler.convert_to_file(py_obj,name)\n#define py_to_file(py_obj,name) x__file_handler.py_to_file(py_obj,name)\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nclass instance_handler\n{\npublic:\n PyObject* convert_to_instance(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_instance(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\ninstance_handler x__instance_handler = instance_handler();\n#define convert_to_instance(py_obj,name) x__instance_handler.convert_to_instance(py_obj,name)\n#define py_to_instance(py_obj,name) x__instance_handler.py_to_instance(py_obj,name)\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nclass callable_handler\n{\npublic: \n PyObject* convert_to_callable(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_callable(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\ncallable_handler x__callable_handler = callable_handler();\n#define convert_to_callable(py_obj,name) x__callable_handler.convert_to_callable(py_obj,name)\n#define py_to_callable(py_obj,name) x__callable_handler.py_to_callable(py_obj,name)\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nclass module_handler\n{\npublic:\n PyObject* convert_to_module(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_module(PyObject* py_obj, const char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nmodule_handler x__module_handler = module_handler();\n#define convert_to_module(py_obj,name) x__module_handler.convert_to_module(py_obj,name)\n#define py_to_module(py_obj,name) x__module_handler.py_to_module(py_obj,name)\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\n# These non-templated version is now used for most scalar conversions.\nnon_template_scalar_support_code = \\\n\"\"\"\n\nclass scalar_handler\n{\npublic: \n int convert_to_int(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n }\n long convert_to_long(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n }\n\n double convert_to_float(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n }\n\n std::complex convert_to_complex(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n }\n\n int py_to_int(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n }\n \n long py_to_long(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n }\n \n double py_to_float(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n }\n \n std::complex py_to_complex(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n }\n\n};\n\nscalar_handler x__scalar_handler = scalar_handler();\n#define convert_to_int(py_obj,name) x__scalar_handler.convert_to_int(py_obj,name)\n#define py_to_int(py_obj,name) x__scalar_handler.py_to_int(py_obj,name)\n\n#define convert_to_long(py_obj,name) x__scalar_handler.convert_to_long(py_obj,name)\n#define py_to_long(py_obj,name) x__scalar_handler.py_to_long(py_obj,name)\n\n#define convert_to_float(py_obj,name) x__scalar_handler.convert_to_float(py_obj,name)\n#define py_to_float(py_obj,name) x__scalar_handler.py_to_float(py_obj,name)\n\n#define convert_to_complex(py_obj,name) x__scalar_handler.convert_to_complex(py_obj,name)\n#define py_to_complex(py_obj,name) x__scalar_handler.py_to_complex(py_obj,name)\n\n\"\"\" \n\n# this code will not build with msvc...\n# This is only used for blitz stuff now. The non-templated\n# version, defined further down, is now used for most code.\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,const char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,const char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n const char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,const char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,const char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n const char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "source_code_before": "\"\"\" C/C++ code strings needed for converting most non-sequence\n Python variables:\n module_support_code -- several routines used by most other code \n conversion methods. It holds the only\n CXX dependent code in this file. The CXX\n stuff is used for exceptions\n file_convert_code\n instance_convert_code\n callable_convert_code\n module_convert_code\n \n scalar_convert_code\n non_template_scalar_support_code \n Scalar conversion covers int, float, double, complex,\n and double complex. While Python doesn't support all these,\n Numeric does and so all of them are made available.\n Python longs are currently converted to C ints. Any\n better way to handle this?\n\"\"\"\n\nimport base_info\n\n#############################################################\n# Basic module support code\n#############################################################\n\nmodule_support_code = \\\n\"\"\"\n\nchar* find_type(PyObject* py_obj)\n{\n if(py_obj == NULL) return \"C NULL value\";\n if(PyCallable_Check(py_obj)) return \"callable\";\n if(PyString_Check(py_obj)) return \"string\";\n if(PyInt_Check(py_obj)) return \"int\";\n if(PyFloat_Check(py_obj)) return \"float\";\n if(PyDict_Check(py_obj)) return \"dict\";\n if(PyList_Check(py_obj)) return \"list\";\n if(PyTuple_Check(py_obj)) return \"tuple\";\n if(PyFile_Check(py_obj)) return \"file\";\n if(PyModule_Check(py_obj)) return \"module\";\n \n //should probably do more intergation (and thinking) on these.\n if(PyCallable_Check(py_obj) && PyInstance_Check(py_obj)) return \"callable\";\n if(PyInstance_Check(py_obj)) return \"instance\"; \n if(PyCallable_Check(py_obj)) return \"callable\";\n return \"unkown type\";\n}\n\nvoid throw_error(PyObject* exc, const char* msg)\n{\n PyErr_SetString(exc, msg);\n throw 1;\n}\n\nvoid handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg); \n}\n\nvoid handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error:, received '%s' type instead of '%s' for variable '%s'\",\n find_type(py_obj),good_type,var_name);\n throw_error(PyExc_TypeError,msg);\n}\n\n\"\"\"\n\n#############################################################\n# File conversion support code\n#############################################################\n\nfile_convert_code = \\\n\"\"\"\n\nclass file_handler\n{\npublic:\n FILE* convert_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n \n FILE* py_to_file(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"file\", name);\n \n // Cleanup code should call DECREF\n Py_INCREF(py_obj);\n return PyFile_AsFile(py_obj);\n }\n};\n\nfile_handler x__file_handler = file_handler();\n\nPyObject* file_to_py(FILE* file, char* name, char* mode)\n{\n PyObject* py_obj = NULL;\n //extern int fclose(FILE *);\n return (PyObject*) PyFile_FromFile(file, name, mode, fclose);\n}\n\n\"\"\"\n\n\n#############################################################\n# Instance conversion code\n#############################################################\n\ninstance_convert_code = \\\n\"\"\"\n\nclass instance_handler\n{\npublic:\n PyObject* convert_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_conversion_error(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_instance(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyFile_Check(py_obj))\n handle_bad_type(py_obj,\"instance\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\ninstance_handler x__instance_handler = instance_handler();\n\nPyObject* instance_to_py(PyObject* instance)\n{\n // Don't think I need to do anything...\n return (PyObject*) instance;\n}\n\n\"\"\"\n\n#############################################################\n# Callable conversion code\n#############################################################\n\ncallable_convert_code = \\\n\"\"\"\n\nclass callable_handler\n{\npublic: \n PyObject* convert_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_conversion_error(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_callable(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyCallable_Check(py_obj))\n handle_bad_type(py_obj,\"callable\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\ncallable_handler x__callable_handler = callable_handler();\n\nPyObject* callable_to_py(PyObject* callable)\n{\n // Don't think I need to do anything...\n return (PyObject*) callable;\n}\n\n\"\"\"\n\n#############################################################\n# Module conversion code\n#############################################################\n\nmodule_convert_code = \\\n\"\"\"\nclass module_handler\n{\npublic:\n PyObject* convert_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_conversion_error(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n \n PyObject* py_to_module(PyObject* py_obj, char* name)\n {\n if (!py_obj || !PyModule_Check(py_obj))\n handle_bad_type(py_obj,\"module\", name);\n \n // Should I INCREF???\n // Py_INCREF(py_obj);\n // just return the raw python pointer.\n return py_obj;\n }\n};\n\nmodule_handler x__module_handler = module_handler();\n\nPyObject* module_to_py(PyObject* module)\n{\n // Don't think I need to do anything...\n return (PyObject*) module;\n}\n\n\"\"\"\n\n#############################################################\n# Scalar conversion code\n#############################################################\n\nimport base_info\n\n# this code will not build with msvc...\nscalar_support_code = \\\n\"\"\"\n// conversion routines\n\ntemplate \nstatic T convert_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double convert_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float convert_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) convert_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex convert_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex convert_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\n/////////////////////////////////\n// standard translation routines\n\ntemplate \nstatic T py_to_scalar(PyObject* py_obj,char* name)\n{\n //never used.\n return (T) 0;\n}\ntemplate<>\nstatic int py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\ntemplate<>\nstatic long py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\ntemplate<> \nstatic double py_to_scalar(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\ntemplate<> \nstatic float py_to_scalar(PyObject* py_obj,char* name)\n{\n return (float) py_to_scalar(py_obj,name);\n}\n\n// complex not checked.\ntemplate<> \nstatic std::complex py_to_scalar >(PyObject* py_obj,\n char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex((float) PyComplex_RealAsDouble(py_obj),\n (float) PyComplex_ImagAsDouble(py_obj)); \n}\ntemplate<> \nstatic std::complex py_to_scalar >(\n PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n\nnon_template_scalar_support_code = \\\n\"\"\"\n\n// Conversion Errors\n\nclass scalar_handler\n{\npublic: \n int convert_to_int(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyInt_Check(py_obj))\n handle_conversion_error(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n }\n long convert_to_long(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyLong_Check(py_obj))\n handle_conversion_error(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n }\n\n double convert_to_float(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_conversion_error(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n }\n\n// complex not checked.\n std::complex convert_to_complex(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_conversion_error(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n }\n};\n\nscalar_handler x__scalar_handler = scalar_handler();\n/////////////////////////////////////\n// The following functions are used for scalar conversions in msvc\n// because it doesn't handle templates as well.\n\nstatic int py_to_int(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyInt_Check(py_obj))\n handle_bad_type(py_obj,\"int\", name);\n return (int) PyInt_AsLong(py_obj);\n}\n\nstatic long py_to_long(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyLong_Check(py_obj))\n handle_bad_type(py_obj,\"long\", name);\n return (long) PyLong_AsLong(py_obj);\n}\n\nstatic double py_to_float(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyFloat_Check(py_obj))\n handle_bad_type(py_obj,\"float\", name);\n return PyFloat_AsDouble(py_obj);\n}\n\n// complex not checked.\nstatic std::complex py_to_complex(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyComplex_Check(py_obj))\n handle_bad_type(py_obj,\"complex\", name);\n return std::complex(PyComplex_RealAsDouble(py_obj),\n PyComplex_ImagAsDouble(py_obj)); \n}\n\"\"\" \n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 422, "complexity": 0, "token_count": 31, "diff_parsed": { "added": [ "void handle_bad_type(PyObject* py_obj, const char* good_type, const char* var_name)", "void handle_conversion_error(PyObject* py_obj, const char* good_type, const char* var_name)", " FILE* convert_to_file(PyObject* py_obj, const char* name)", " FILE* py_to_file(PyObject* py_obj, const char* name)", "#define convert_to_file(py_obj,name) x__file_handler.convert_to_file(py_obj,name)", "#define py_to_file(py_obj,name) x__file_handler.py_to_file(py_obj,name)", " PyObject* convert_to_instance(PyObject* py_obj, const char* name)", " PyObject* py_to_instance(PyObject* py_obj, const char* name)", "#define convert_to_instance(py_obj,name) x__instance_handler.convert_to_instance(py_obj,name)", "#define py_to_instance(py_obj,name) x__instance_handler.py_to_instance(py_obj,name)", " PyObject* convert_to_callable(PyObject* py_obj, const char* name)", " PyObject* py_to_callable(PyObject* py_obj, const char* name)", "#define convert_to_callable(py_obj,name) x__callable_handler.convert_to_callable(py_obj,name)", "#define py_to_callable(py_obj,name) x__callable_handler.py_to_callable(py_obj,name)", " PyObject* convert_to_module(PyObject* py_obj, const char* name)", " PyObject* py_to_module(PyObject* py_obj, const char* name)", "#define convert_to_module(py_obj,name) x__module_handler.convert_to_module(py_obj,name)", "#define py_to_module(py_obj,name) x__module_handler.py_to_module(py_obj,name)", "# These non-templated version is now used for most scalar conversions.", "non_template_scalar_support_code = \\", "\"\"\"", "", "class scalar_handler", "{", "public:", " int convert_to_int(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyInt_Check(py_obj))", " handle_conversion_error(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", " }", " long convert_to_long(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyLong_Check(py_obj))", " handle_conversion_error(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", " }", "", " double convert_to_float(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_conversion_error(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", " }", "", " std::complex convert_to_complex(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", " }", "", " int py_to_int(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyInt_Check(py_obj))", " handle_bad_type(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", " }", "", " long py_to_long(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyLong_Check(py_obj))", " handle_bad_type(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", " }", "", " double py_to_float(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_bad_type(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", " }", "", " std::complex py_to_complex(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_bad_type(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", " }", "", "};", "", "scalar_handler x__scalar_handler = scalar_handler();", "#define convert_to_int(py_obj,name) x__scalar_handler.convert_to_int(py_obj,name)", "#define py_to_int(py_obj,name) x__scalar_handler.py_to_int(py_obj,name)", "", "#define convert_to_long(py_obj,name) x__scalar_handler.convert_to_long(py_obj,name)", "#define py_to_long(py_obj,name) x__scalar_handler.py_to_long(py_obj,name)", "", "#define convert_to_float(py_obj,name) x__scalar_handler.convert_to_float(py_obj,name)", "#define py_to_float(py_obj,name) x__scalar_handler.py_to_float(py_obj,name)", "", "#define convert_to_complex(py_obj,name) x__scalar_handler.convert_to_complex(py_obj,name)", "#define py_to_complex(py_obj,name) x__scalar_handler.py_to_complex(py_obj,name)", "", "\"\"\"", "# This is only used for blitz stuff now. The non-templated", "# version, defined further down, is now used for most code.", "static T convert_to_scalar(PyObject* py_obj,const char* name)", "static int convert_to_scalar(PyObject* py_obj,const char* name)", "static long convert_to_scalar(PyObject* py_obj,const char* name)", "static double convert_to_scalar(PyObject* py_obj,const char* name)", "static float convert_to_scalar(PyObject* py_obj,const char* name)", " const char* name)", " PyObject* py_obj,const char* name)", "static T py_to_scalar(PyObject* py_obj,const char* name)", "static int py_to_scalar(PyObject* py_obj,const char* name)", "static long py_to_scalar(PyObject* py_obj,const char* name)", "static double py_to_scalar(PyObject* py_obj,const char* name)", "static float py_to_scalar(PyObject* py_obj,const char* name)", " const char* name)", " PyObject* py_obj,const char* name)" ], "deleted": [ "void handle_bad_type(PyObject* py_obj, char* good_type, char* var_name)", "void handle_conversion_error(PyObject* py_obj, char* good_type, char* var_name)", " FILE* convert_to_file(PyObject* py_obj, char* name)", " FILE* py_to_file(PyObject* py_obj, char* name)", " PyObject* convert_to_instance(PyObject* py_obj, char* name)", " PyObject* py_to_instance(PyObject* py_obj, char* name)", " PyObject* convert_to_callable(PyObject* py_obj, char* name)", " PyObject* py_to_callable(PyObject* py_obj, char* name)", " PyObject* convert_to_module(PyObject* py_obj, char* name)", " PyObject* py_to_module(PyObject* py_obj, char* name)", "import base_info", "static T convert_to_scalar(PyObject* py_obj,char* name)", "static int convert_to_scalar(PyObject* py_obj,char* name)", "static long convert_to_scalar(PyObject* py_obj,char* name)", "static double convert_to_scalar(PyObject* py_obj,char* name)", "static float convert_to_scalar(PyObject* py_obj,char* name)", " char* name)", " PyObject* py_obj,char* name)", "static T py_to_scalar(PyObject* py_obj,char* name)", "static int py_to_scalar(PyObject* py_obj,char* name)", "static long py_to_scalar(PyObject* py_obj,char* name)", "static double py_to_scalar(PyObject* py_obj,char* name)", "static float py_to_scalar(PyObject* py_obj,char* name)", " char* name)", " PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_bad_type(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", "}", "\"\"\"", "", "non_template_scalar_support_code = \\", "\"\"\"", "", "// Conversion Errors", "", "class scalar_handler", "{", "public:", " int convert_to_int(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyInt_Check(py_obj))", " handle_conversion_error(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", " }", " long convert_to_long(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyLong_Check(py_obj))", " handle_conversion_error(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", " }", "", " double convert_to_float(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_conversion_error(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", " }", "", "// complex not checked.", " std::complex convert_to_complex(PyObject* py_obj,char* name)", " {", " if (!py_obj || !PyComplex_Check(py_obj))", " handle_conversion_error(py_obj,\"complex\", name);", " return std::complex(PyComplex_RealAsDouble(py_obj),", " PyComplex_ImagAsDouble(py_obj));", " }", "};", "", "scalar_handler x__scalar_handler = scalar_handler();", "/////////////////////////////////////", "// The following functions are used for scalar conversions in msvc", "// because it doesn't handle templates as well.", "", "static int py_to_int(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyInt_Check(py_obj))", " handle_bad_type(py_obj,\"int\", name);", " return (int) PyInt_AsLong(py_obj);", "}", "", "static long py_to_long(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyLong_Check(py_obj))", " handle_bad_type(py_obj,\"long\", name);", " return (long) PyLong_AsLong(py_obj);", "}", "", "static double py_to_float(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyFloat_Check(py_obj))", " handle_bad_type(py_obj,\"float\", name);", " return PyFloat_AsDouble(py_obj);", "}", "", "// complex not checked.", "static std::complex py_to_complex(PyObject* py_obj,char* name)" ] } }, { "old_path": "weave/cxx_info.py", "new_path": "weave/cxx_info.py", "filename": "cxx_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -5,23 +5,24 @@\n class string_handler\n {\n public:\n- static Py::String convert_to_string(PyObject* py_obj,char* name)\n+ static Py::String convert_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n+ Py::String py_to_string(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyString_Check(py_obj))\n+ handle_bad_type(py_obj,\"string\", name);\n+ return Py::String(py_obj);\n+ }\n };\n \n string_handler x__string_handler = string_handler();\n \n-static Py::String py_to_string(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyString_Check(py_obj))\n- handle_bad_type(py_obj,\"string\", name);\n- return Py::String(py_obj);\n-}\n-\n+#define convert_to_string(py_obj,name) x__string_handler.convert_to_string(py_obj,name)\n+#define py_to_string(py_obj,name) x__string_handler.py_to_string(py_obj,name)\n \"\"\"\n \n list_support_code = \\\n@@ -30,7 +31,7 @@ class string_handler\n class list_handler\n {\n public:\n- Py::List convert_to_list(PyObject* py_obj,char* name)\n+ Py::List convert_to_list(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n@@ -40,7 +41,7 @@ class list_handler\n \n list_handler x__list_handler = list_handler();\n \n-static Py::List py_to_list(PyObject* py_obj,char* name)\n+static Py::List py_to_list(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n@@ -53,22 +54,24 @@ class list_handler\n class dict_handler\n {\n public:\n- Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n+ Py::Dict convert_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n+ Py::Dict py_to_dict(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyDict_Check(py_obj))\n+ handle_bad_type(py_obj,\"dict\", name);\n+ return Py::Dict(py_obj);\n+ }\n };\n \n dict_handler x__dict_handler = dict_handler();\n+#define convert_to_dict(py_obj,name) x__dict_handler.convert_to_dict(py_obj,name)\n+#define py_to_dict(py_obj,name) x__dict_handler.py_to_dict(py_obj,name)\n \n-static Py::Dict py_to_dict(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyDict_Check(py_obj))\n- handle_bad_type(py_obj,\"dict\", name);\n- return Py::Dict(py_obj);\n-}\n \"\"\"\n \n tuple_support_code = \\\n@@ -76,22 +79,23 @@ class dict_handler\n class tuple_handler\n {\n public:\n- Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n+ Py::Tuple convert_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n+ Py::Tuple py_to_tuple(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyTuple_Check(py_obj))\n+ handle_bad_type(py_obj,\"tuple\", name);\n+ return Py::Tuple(py_obj);\n+ }\n };\n \n tuple_handler x__tuple_handler = tuple_handler();\n-\n-static Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n-{\n- if (!py_obj || !PyTuple_Check(py_obj))\n- handle_bad_type(py_obj,\"tuple\", name);\n- return Py::Tuple(py_obj);\n-}\n+#define convert_to_tuple(py_obj,name) x__tuple_handler.convert_to_tuple(py_obj,name)\n+#define py_to_tuple(py_obj,name) x__tuple_handler.py_to_tuple(py_obj,name)\n \"\"\"\n \n import os, cxx_info\n", "added_lines": 29, "deleted_lines": 25, "source_code": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\npublic:\n static Py::String convert_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n Py::String py_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\n\nstring_handler x__string_handler = string_handler();\n\n#define convert_to_string(py_obj,name) x__string_handler.convert_to_string(py_obj,name)\n#define py_to_string(py_obj,name) x__string_handler.py_to_string(py_obj,name)\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\npublic:\n Py::List convert_to_list(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nlist_handler x__list_handler = list_handler();\n\nstatic Py::List py_to_list(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\npublic:\n Py::Dict convert_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n Py::Dict py_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n};\n\ndict_handler x__dict_handler = dict_handler();\n#define convert_to_dict(py_obj,name) x__dict_handler.convert_to_dict(py_obj,name)\n#define py_to_dict(py_obj,name) x__dict_handler.py_to_dict(py_obj,name)\n\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\npublic:\n Py::Tuple convert_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n Py::Tuple py_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\ntuple_handler x__tuple_handler = tuple_handler();\n#define convert_to_tuple(py_obj,name) x__tuple_handler.convert_to_tuple(py_obj,name)\n#define py_to_tuple(py_obj,name) x__tuple_handler.py_to_tuple(py_obj,name)\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "source_code_before": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\npublic:\n static Py::String convert_to_string(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\n\nstring_handler x__string_handler = string_handler();\n\nstatic Py::String py_to_string(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n}\n\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\npublic:\n Py::List convert_to_list(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nlist_handler x__list_handler = list_handler();\n\nstatic Py::List py_to_list(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\npublic:\n Py::Dict convert_to_dict(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n};\n\ndict_handler x__dict_handler = dict_handler();\n\nstatic Py::Dict py_to_dict(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n}\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\npublic:\n Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\ntuple_handler x__tuple_handler = tuple_handler();\n\nstatic Py::Tuple py_to_tuple(PyObject* py_obj,char* name)\n{\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n}\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 107, "complexity": 0, "token_count": 137, "diff_parsed": { "added": [ " static Py::String convert_to_string(PyObject* py_obj,const char* name)", " Py::String py_to_string(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyString_Check(py_obj))", " handle_bad_type(py_obj,\"string\", name);", " return Py::String(py_obj);", " }", "#define convert_to_string(py_obj,name) x__string_handler.convert_to_string(py_obj,name)", "#define py_to_string(py_obj,name) x__string_handler.py_to_string(py_obj,name)", " Py::List convert_to_list(PyObject* py_obj,const char* name)", "static Py::List py_to_list(PyObject* py_obj,const char* name)", " Py::Dict convert_to_dict(PyObject* py_obj,const char* name)", " Py::Dict py_to_dict(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyDict_Check(py_obj))", " handle_bad_type(py_obj,\"dict\", name);", " return Py::Dict(py_obj);", " }", "#define convert_to_dict(py_obj,name) x__dict_handler.convert_to_dict(py_obj,name)", "#define py_to_dict(py_obj,name) x__dict_handler.py_to_dict(py_obj,name)", " Py::Tuple convert_to_tuple(PyObject* py_obj,const char* name)", " Py::Tuple py_to_tuple(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyTuple_Check(py_obj))", " handle_bad_type(py_obj,\"tuple\", name);", " return Py::Tuple(py_obj);", " }", "#define convert_to_tuple(py_obj,name) x__tuple_handler.convert_to_tuple(py_obj,name)", "#define py_to_tuple(py_obj,name) x__tuple_handler.py_to_tuple(py_obj,name)" ], "deleted": [ " static Py::String convert_to_string(PyObject* py_obj,char* name)", "static Py::String py_to_string(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyString_Check(py_obj))", " handle_bad_type(py_obj,\"string\", name);", " return Py::String(py_obj);", "}", "", " Py::List convert_to_list(PyObject* py_obj,char* name)", "static Py::List py_to_list(PyObject* py_obj,char* name)", " Py::Dict convert_to_dict(PyObject* py_obj,char* name)", "static Py::Dict py_to_dict(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyDict_Check(py_obj))", " handle_bad_type(py_obj,\"dict\", name);", " return Py::Dict(py_obj);", "}", " Py::Tuple convert_to_tuple(PyObject* py_obj,char* name)", "", "static Py::Tuple py_to_tuple(PyObject* py_obj,char* name)", "{", " if (!py_obj || !PyTuple_Check(py_obj))", " handle_bad_type(py_obj,\"tuple\", name);", " return Py::Tuple(py_obj);", "}" ] } }, { "old_path": "weave/scalar_spec.py", "new_path": "weave/scalar_spec.py", "filename": "scalar_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -58,14 +58,14 @@ def template_decl_code(self,template = 0,inline=0):\n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n- ValueError, 'msvc compiler does not support templated scalar code.'\\\n- 'try mingw32 instead (www.mingw.org).'\n+ ValueError, 'msvc compiler does not support templated scalar '\\\n+ 'code. try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n- 'x__scalar_handler.convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n+ 'convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n", "added_lines": 3, "deleted_lines": 3, "source_code": "from base_spec import base_specification\nimport scalar_info\n#from Numeric import *\nfrom types import *\n\n# the following typemaps are for 32 bit platforms. A way to do this\n# general case? maybe ask numeric types how long they are and base\n# the decisions on that.\n\nnumeric_to_blitz_type_mapping = {}\n\nnumeric_to_blitz_type_mapping['T'] = 'T' # for templates\nnumeric_to_blitz_type_mapping['F'] = 'std::complex '\nnumeric_to_blitz_type_mapping['D'] = 'std::complex '\nnumeric_to_blitz_type_mapping['f'] = 'float'\nnumeric_to_blitz_type_mapping['d'] = 'double'\nnumeric_to_blitz_type_mapping['1'] = 'char'\nnumeric_to_blitz_type_mapping['b'] = 'unsigned char'\nnumeric_to_blitz_type_mapping['s'] = 'short'\nnumeric_to_blitz_type_mapping['i'] = 'int'\n# not strictly correct, but shoulld be fine fo numeric work.\n# add test somewhere to make sure long can be cast to int before using.\nnumeric_to_blitz_type_mapping['l'] = 'int'\n\n# standard Python numeric type mappings.\nnumeric_to_blitz_type_mapping[type(1)] = 'int'\nnumeric_to_blitz_type_mapping[type(1.)] = 'double'\nnumeric_to_blitz_type_mapping[type(1.+1.j)] = 'std::complex '\n#hmmm. The following is likely unsafe...\nnumeric_to_blitz_type_mapping[type(1L)] = 'int'\n\nclass scalar_specification(base_specification):\n _build_information = [scalar_info.scalar_info()] \n\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name\n new_spec.numeric_type = type(value)\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n #if self.compiler == 'msvc':\n # return self.msvc_decl_code(templatize,inline)\n #else:\n # return self.template_decl_code(templatize,inline) \\\n return self.msvc_decl_code(templatize,inline)\n\n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_scalar<%(type)s >(%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n ValueError, 'msvc compiler does not support templated scalar '\\\n 'code. try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n\n #def c_function_declaration_code(self):\n # code = '%s &%s\" % \\\n # (numeric_to_blitz_type_mapping[self.numeric_type], self.name)\n # return code\n\n def __repr__(self):\n msg = \"(%s:: name: %s, type: %s)\" % \\\n (self.type_name,self.name, self.numeric_type)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.__class__, other.__class__)\n\nclass int_specification(scalar_specification):\n type_name = 'int'\n def type_match(self,value):\n return type(value) in [IntType, LongType]\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Int(%s);\\n' % (self.name,self.name) \n return code\n \nclass float_specification(scalar_specification):\n type_name = 'float'\n def type_match(self,value):\n return type(value) in [FloatType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Float(%s);\\n' % (self.name,self.name) \n return code\n\nclass complex_specification(scalar_specification):\n type_name = 'complex'\n def type_match(self,value):\n return type(value) in [ComplexType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Complex(%s.real(),%s.imag());\\n' % \\\n (self.name,self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n ", "source_code_before": "from base_spec import base_specification\nimport scalar_info\n#from Numeric import *\nfrom types import *\n\n# the following typemaps are for 32 bit platforms. A way to do this\n# general case? maybe ask numeric types how long they are and base\n# the decisions on that.\n\nnumeric_to_blitz_type_mapping = {}\n\nnumeric_to_blitz_type_mapping['T'] = 'T' # for templates\nnumeric_to_blitz_type_mapping['F'] = 'std::complex '\nnumeric_to_blitz_type_mapping['D'] = 'std::complex '\nnumeric_to_blitz_type_mapping['f'] = 'float'\nnumeric_to_blitz_type_mapping['d'] = 'double'\nnumeric_to_blitz_type_mapping['1'] = 'char'\nnumeric_to_blitz_type_mapping['b'] = 'unsigned char'\nnumeric_to_blitz_type_mapping['s'] = 'short'\nnumeric_to_blitz_type_mapping['i'] = 'int'\n# not strictly correct, but shoulld be fine fo numeric work.\n# add test somewhere to make sure long can be cast to int before using.\nnumeric_to_blitz_type_mapping['l'] = 'int'\n\n# standard Python numeric type mappings.\nnumeric_to_blitz_type_mapping[type(1)] = 'int'\nnumeric_to_blitz_type_mapping[type(1.)] = 'double'\nnumeric_to_blitz_type_mapping[type(1.+1.j)] = 'std::complex '\n#hmmm. The following is likely unsafe...\nnumeric_to_blitz_type_mapping[type(1L)] = 'int'\n\nclass scalar_specification(base_specification):\n _build_information = [scalar_info.scalar_info()] \n\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name\n new_spec.numeric_type = type(value)\n return new_spec\n \n def declaration_code(self,templatize = 0,inline=0):\n #if self.compiler == 'msvc':\n # return self.msvc_decl_code(templatize,inline)\n #else:\n # return self.template_decl_code(templatize,inline) \\\n return self.msvc_decl_code(templatize,inline)\n\n def template_decl_code(self,template = 0,inline=0):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'convert_to_scalar<%(type)s >(%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n \n def msvc_decl_code(self,template = 0,inline=0):\n # doesn't support template = 1\n if template:\n ValueError, 'msvc compiler does not support templated scalar code.'\\\n 'try mingw32 instead (www.mingw.org).'\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n func_type = self.type_name\n name = self.name\n var_name = self.retrieve_py_variable(inline)\n template = '%(type)s %(name)s = '\\\n 'x__scalar_handler.convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'\n code = template % locals()\n return code\n\n #def c_function_declaration_code(self):\n # code = '%s &%s\" % \\\n # (numeric_to_blitz_type_mapping[self.numeric_type], self.name)\n # return code\n\n def __repr__(self):\n msg = \"(%s:: name: %s, type: %s)\" % \\\n (self.type_name,self.name, self.numeric_type)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.__class__, other.__class__)\n\nclass int_specification(scalar_specification):\n type_name = 'int'\n def type_match(self,value):\n return type(value) in [IntType, LongType]\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Int(%s);\\n' % (self.name,self.name) \n return code\n \nclass float_specification(scalar_specification):\n type_name = 'float'\n def type_match(self,value):\n return type(value) in [FloatType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Float(%s);\\n' % (self.name,self.name) \n return code\n\nclass complex_specification(scalar_specification):\n type_name = 'complex'\n def type_match(self,value):\n return type(value) in [ComplexType]\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = Py::Complex(%s.real(),%s.imag());\\n' % \\\n (self.name,self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n ", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [ "self", "name", "value" ], "start_line": 35, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "template_decl_code", "long_name": "template_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 8, "complexity": 1, "token_count": 48, "parameters": [ "self", "template", "inline" ], "start_line": 49, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 12, "complexity": 2, "token_count": 61, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 77, "end_line": 80, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 3, "token_count": 42, "parameters": [ "self", "other" ], "start_line": 81, "end_line": 85, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 18, "parameters": [ "self", "value" ], "start_line": 89, "end_line": 90, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 92, "end_line": 94, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 98, "end_line": 99, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 100, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 106, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 108, "end_line": 111, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 113, "end_line": 115, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 117, "end_line": 119, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "scalar_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [ "self", "name", "value" ], "start_line": 35, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "template_decl_code", "long_name": "template_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 8, "complexity": 1, "token_count": 48, "parameters": [ "self", "template", "inline" ], "start_line": 49, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 12, "complexity": 2, "token_count": 61, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 77, "end_line": 80, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 3, "token_count": 42, "parameters": [ "self", "other" ], "start_line": 81, "end_line": 85, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 18, "parameters": [ "self", "value" ], "start_line": 89, "end_line": 90, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 92, "end_line": 94, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 98, "end_line": 99, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 100, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "scalar_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 106, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "scalar_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 108, "end_line": 111, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 113, "end_line": 115, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "scalar_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 117, "end_line": 119, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "msvc_decl_code", "long_name": "msvc_decl_code( self , template = 0 , inline = 0 )", "filename": "scalar_spec.py", "nloc": 12, "complexity": 2, "token_count": 61, "parameters": [ "self", "template", "inline" ], "start_line": 58, "end_line": 70, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 } ], "nloc": 82, "complexity": 16, "token_count": 536, "diff_parsed": { "added": [ " ValueError, 'msvc compiler does not support templated scalar '\\", " 'code. try mingw32 instead (www.mingw.org).'", " 'convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'" ], "deleted": [ " ValueError, 'msvc compiler does not support templated scalar code.'\\", " 'try mingw32 instead (www.mingw.org).'", " 'x__scalar_handler.convert_to_%(func_type)s (%(var_name)s,\"%(name)s\");\\n'" ] } }, { "old_path": "weave/sequence_spec.py", "new_path": "weave/sequence_spec.py", "filename": "sequence_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -25,7 +25,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::String %s = x__string_handler.convert_to_string(%s,\"%s\");\\n' % \\\n+ code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n@@ -40,7 +40,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::List %s = x__list_handler.convert_to_list(%s,\"%s\");\\n' % \\\n+ code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n@@ -69,7 +69,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::Tuple %s = x__tuple_handler.convert_to_tuple(%s,\"%s\");\\n' % \\\n+ code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n", "added_lines": 3, "deleted_lines": 3, "source_code": "import cxx_info\nfrom base_spec import base_specification\nfrom types import *\nimport os\n\nclass base_cxx_specification(base_specification):\n _build_information = [cxx_info.cxx_info()]\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(%s:: name: %s)\" % (self.type_name,self.name)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \nclass string_specification(base_cxx_specification):\n type_name = 'string'\n def type_match(self,value):\n return type(value) in [StringType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\n\nclass list_specification(base_cxx_specification):\n type_name = 'list'\n def type_match(self,value):\n return type(value) in [ListType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass dict_specification(base_cxx_specification):\n type_name = 'dict'\n def type_match(self,value):\n return type(value) in [DictType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass tuple_specification(base_cxx_specification):\n type_name = 'tuple'\n def type_match(self,value):\n return type(value) in [TupleType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n", "source_code_before": "import cxx_info\nfrom base_spec import base_specification\nfrom types import *\nimport os\n\nclass base_cxx_specification(base_specification):\n _build_information = [cxx_info.cxx_info()]\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(%s:: name: %s)\" % (self.type_name,self.name)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \nclass string_specification(base_cxx_specification):\n type_name = 'string'\n def type_match(self,value):\n return type(value) in [StringType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::String %s = x__string_handler.convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\n\nclass list_specification(base_cxx_specification):\n type_name = 'list'\n def type_match(self,value):\n return type(value) in [ListType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::List %s = x__list_handler.convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass dict_specification(base_cxx_specification):\n type_name = 'dict'\n def type_match(self,value):\n return type(value) in [DictType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass tuple_specification(base_cxx_specification):\n type_name = 'tuple'\n def type_match(self,value):\n return type(value) in [TupleType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Tuple %s = x__tuple_handler.convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "sequence_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 8, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 16, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 23, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 38, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 41, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 46, "end_line": 48, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 52, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 67, "end_line": 68, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 70, "end_line": 74, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 75, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "sequence_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 8, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 16, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 23, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 38, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 41, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 46, "end_line": 48, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 52, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 67, "end_line": 68, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 70, "end_line": 74, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 75, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 } ], "changed_methods": [ { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 } ], "nloc": 64, "complexity": 16, "token_count": 451, "diff_parsed": { "added": [ " code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\", " code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\", " code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\" ], "deleted": [ " code = 'Py::String %s = x__string_handler.convert_to_string(%s,\"%s\");\\n' % \\", " code = 'Py::List %s = x__list_handler.convert_to_list(%s,\"%s\");\\n' % \\", " code = 'Py::Tuple %s = x__tuple_handler.convert_to_tuple(%s,\"%s\");\\n' % \\" ] } } ] }, { "hash": "d6ea23e4036e4f20550e317bfa3b43fbc98c05f6", "msg": "fixed const char* in standard_array_info.py", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T18:33:19+00:00", "author_timezone": 0, "committer_date": "2002-01-17T18:33:19+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "0c8b48993f0556810bc18449854f00d1938f60d3" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 6, "insertions": 8, "lines": 14, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/standard_array_info.py", "new_path": "weave/standard_array_info.py", "filename": "standard_array_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -6,7 +6,7 @@\n \n array_convert_code = \\\n \"\"\"\n-static PyArrayObject* convert_to_numpy(PyObject* py_obj, char* name)\n+static PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)\n {\n PyArrayObject* arr_obj = NULL;\n \n@@ -18,7 +18,7 @@\n return (PyArrayObject*) py_obj;\n }\n \n-static PyArrayObject* py_to_numpy(PyObject* py_obj, char* name)\n+static PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)\n {\n PyArrayObject* arr_obj = NULL;\n \n@@ -34,7 +34,8 @@\n \n type_check_code = \\\n \"\"\"\n-void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n+void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,\n+ const char* name)\n {\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n@@ -49,7 +50,7 @@\n }\n }\n \n-void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n+void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)\n {\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n@@ -67,7 +68,8 @@\n \n size_check_code = \\\n \"\"\"\n-void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n+void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, \n+ const char* name)\n {\n if (arr_obj->nd != Ndims)\n {\n@@ -78,7 +80,7 @@\n } \n }\n \n-void numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n+void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)\n {\n if (arr_obj->nd != Ndims)\n {\n", "added_lines": 8, "deleted_lines": 6, "source_code": "\"\"\" Generic support code for handling standard Numeric arrays \n\"\"\"\n\nimport base_info\n\n\narray_convert_code = \\\n\"\"\"\nstatic PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_conversion_error(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\nstatic PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_bad_type(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\n\"\"\"\n\ntype_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,\n const char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\nvoid numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\"\"\"\n\nsize_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, \n const char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\nvoid numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\"\"\"\n\nnumeric_init_code = \\\n\"\"\"\nPy_Initialize();\nimport_array();\nPyImport_ImportModule(\"Numeric\");\n\"\"\"\n\nclass array_info(base_info.base_info):\n _headers = ['\"Numeric/arrayobject.h\"','','']\n _support_code = [array_convert_code,size_check_code, type_check_code]\n _module_init_code = [numeric_init_code] ", "source_code_before": "\"\"\" Generic support code for handling standard Numeric arrays \n\"\"\"\n\nimport base_info\n\n\narray_convert_code = \\\n\"\"\"\nstatic PyArrayObject* convert_to_numpy(PyObject* py_obj, char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_conversion_error(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\nstatic PyArrayObject* py_to_numpy(PyObject* py_obj, char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_bad_type(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\n\"\"\"\n\ntype_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\nvoid numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\"\"\"\n\nsize_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\nvoid numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\"\"\"\n\nnumeric_init_code = \\\n\"\"\"\nPy_Initialize();\nimport_array();\nPyImport_ImportModule(\"Numeric\");\n\"\"\"\n\nclass array_info(base_info.base_info):\n _headers = ['\"Numeric/arrayobject.h\"','','']\n _support_code = [array_convert_code,size_check_code, type_check_code]\n _module_init_code = [numeric_init_code] ", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 98, "complexity": 0, "token_count": 50, "diff_parsed": { "added": [ "static PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)", "static PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)", "void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,", " const char* name)", "void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)", "void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims,", " const char* name)", "void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)" ], "deleted": [ "static PyArrayObject* convert_to_numpy(PyObject* py_obj, char* name)", "static PyArrayObject* py_to_numpy(PyObject* py_obj, char* name)", "void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)", "void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, char* name)", "void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)", "void numpy_check_size(PyArrayObject* arr_obj, int Ndims, char* name)" ] } } ] }, { "hash": "5e9fe5d6a531bce42b13c88b8b3fb8b28de9b828", "msg": "turned off verbosity in blitz tests so that testing didn't spew so much stuff.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T18:37:46+00:00", "author_timezone": 0, "committer_date": "2002-01-17T18:37:46+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "d6ea23e4036e4f20550e317bfa3b43fbc98c05f6" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 1, "lines": 2, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/tests/test_blitz_tools.py", "new_path": "weave/tests/test_blitz_tools.py", "filename": "test_blitz_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -81,7 +81,7 @@ def generic_test(self,expr,arg_dict,type,size,mod_location):\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n- blitz_tools.blitz(expr,arg_dict,{},verbose=2) #,\n+ blitz_tools.blitz(expr,arg_dict,{},verbose) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n", "added_lines": 1, "deleted_lines": 1, "source_code": "import unittest\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \nimport RandomArray\nimport os\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path,restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport blitz_tools\nfrom ast_tools import *\nfrom weave_test_utils import *\nrestore_path()\n\nadd_local_to_path(__name__)\nimport test_scalar_spec\nrestore_path()\n\nclass test_ast_to_blitz_expr(unittest.TestCase):\n\n def generic_test(self,expr,desired):\n import parser\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n actual = blitz_tools.ast_to_blitz_expr(ast_list)\n actual = remove_whitespace(actual)\n desired = remove_whitespace(desired)\n print_assert_equal(expr,actual,desired)\n\n def check_simple_expr(self):\n \"\"\"convert simple expr to blitz\n \n a[:1:2] = b[:1+i+2:]\n \"\"\"\n expr = \"a[:1:2] = b[:1+i+2:]\" \n desired = \"a(blitz::Range(_beg,1-1,2))=\"\\\n \"b(blitz::Range(_beg,1+i+2-1));\"\n self.generic_test(expr,desired)\n\n def check_fdtd_expr(self):\n \"\"\" convert fdtd equation to blitz.\n ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] \n + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\n - cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1]);\n Note: This really should have \"\\\" at the end of each line\n to indicate continuation. \n \"\"\"\n expr = \"ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n desired = 'ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))='\\\n ' ca_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' *ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '+cb_y_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hz(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' -hz(_all,blitz::Range(_beg,_Nhz(1)-1-1),_all))'\\\n ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,_Nhy(2)-1-1)));'\n self.generic_test(expr,desired)\n\nclass test_blitz(unittest.TestCase):\n \"\"\"* These are long running tests...\n \n I'd like to benchmark these things somehow.\n *\"\"\"\n def generic_test(self,expr,arg_dict,type,size,mod_location):\n clean_result = array(arg_dict['result'],copy=1)\n t1 = time.time()\n exec expr in globals(),arg_dict\n t2 = time.time()\n standard = t2 - t1\n desired = arg_dict['result']\n arg_dict['result'] = clean_result\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n blitz_tools.blitz(expr,arg_dict,{},verbose) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n actual = arg_dict['result']\n # this really should give more info...\n try:\n # this isn't very stringent. Need to tighten this up and\n # learn where failures are occuring.\n assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))\n except:\n diff = actual-desired\n print diff[:4,:4]\n print diff[:4,-4:]\n print diff[-4:,:4]\n print diff[-4:,-4:]\n print sum(abs(diff.flat)) \n raise AssertionError \n return standard,compiled\n \n def generic_2d(self,expr):\n \"\"\" The complex testing is pretty lame...\n \"\"\"\n mod_location = empty_temp_dir()\n import parser\n ast = parser.suite(expr)\n arg_list = harvest_variables(ast.tolist())\n #print arg_list\n all_types = [Float32,Float64,Complex32,Complex64]\n all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)]\n print '\\nExpression:', expr\n for typ in all_types:\n for size in all_sizes:\n result = zeros(size,typ)\n arg_dict = {}\n for arg in arg_list:\n arg_dict[arg] = RandomArray.normal(0,1,size).astype(typ)\n arg_dict[arg].savespace(1)\n # set imag part of complex values to non-zero value\n try: arg_dict[arg].imag = arg_dict[arg].real\n except: pass \n print 'Run:', size,typ\n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1.\n print \"1st run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up) \n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1. \n print \"2nd run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up)\n cleanup_temp_dir(mod_location) \n #def check_simple_2d(self):\n # \"\"\" result = a + b\"\"\" \n # expr = \"result = a + b\"\n # self.generic_2d(expr)\n def check_5point_avg_2d(self):\n \"\"\" result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\n + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n \"\"\" \n expr = \"result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n self.generic_2d(expr)\n \ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_ast_to_blitz_expr,'check_') )\n suites.append( unittest.makeSuite(test_blitz,'check_') ) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "source_code_before": "import unittest\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \nimport RandomArray\nimport os\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path,restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport blitz_tools\nfrom ast_tools import *\nfrom weave_test_utils import *\nrestore_path()\n\nadd_local_to_path(__name__)\nimport test_scalar_spec\nrestore_path()\n\nclass test_ast_to_blitz_expr(unittest.TestCase):\n\n def generic_test(self,expr,desired):\n import parser\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n actual = blitz_tools.ast_to_blitz_expr(ast_list)\n actual = remove_whitespace(actual)\n desired = remove_whitespace(desired)\n print_assert_equal(expr,actual,desired)\n\n def check_simple_expr(self):\n \"\"\"convert simple expr to blitz\n \n a[:1:2] = b[:1+i+2:]\n \"\"\"\n expr = \"a[:1:2] = b[:1+i+2:]\" \n desired = \"a(blitz::Range(_beg,1-1,2))=\"\\\n \"b(blitz::Range(_beg,1+i+2-1));\"\n self.generic_test(expr,desired)\n\n def check_fdtd_expr(self):\n \"\"\" convert fdtd equation to blitz.\n ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] \n + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\n - cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1]);\n Note: This really should have \"\\\" at the end of each line\n to indicate continuation. \n \"\"\"\n expr = \"ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n desired = 'ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))='\\\n ' ca_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' *ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '+cb_y_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hz(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' -hz(_all,blitz::Range(_beg,_Nhz(1)-1-1),_all))'\\\n ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,_Nhy(2)-1-1)));'\n self.generic_test(expr,desired)\n\nclass test_blitz(unittest.TestCase):\n \"\"\"* These are long running tests...\n \n I'd like to benchmark these things somehow.\n *\"\"\"\n def generic_test(self,expr,arg_dict,type,size,mod_location):\n clean_result = array(arg_dict['result'],copy=1)\n t1 = time.time()\n exec expr in globals(),arg_dict\n t2 = time.time()\n standard = t2 - t1\n desired = arg_dict['result']\n arg_dict['result'] = clean_result\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n blitz_tools.blitz(expr,arg_dict,{},verbose=2) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n actual = arg_dict['result']\n # this really should give more info...\n try:\n # this isn't very stringent. Need to tighten this up and\n # learn where failures are occuring.\n assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))\n except:\n diff = actual-desired\n print diff[:4,:4]\n print diff[:4,-4:]\n print diff[-4:,:4]\n print diff[-4:,-4:]\n print sum(abs(diff.flat)) \n raise AssertionError \n return standard,compiled\n \n def generic_2d(self,expr):\n \"\"\" The complex testing is pretty lame...\n \"\"\"\n mod_location = empty_temp_dir()\n import parser\n ast = parser.suite(expr)\n arg_list = harvest_variables(ast.tolist())\n #print arg_list\n all_types = [Float32,Float64,Complex32,Complex64]\n all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)]\n print '\\nExpression:', expr\n for typ in all_types:\n for size in all_sizes:\n result = zeros(size,typ)\n arg_dict = {}\n for arg in arg_list:\n arg_dict[arg] = RandomArray.normal(0,1,size).astype(typ)\n arg_dict[arg].savespace(1)\n # set imag part of complex values to non-zero value\n try: arg_dict[arg].imag = arg_dict[arg].real\n except: pass \n print 'Run:', size,typ\n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1.\n print \"1st run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up) \n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1. \n print \"2nd run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up)\n cleanup_temp_dir(mod_location) \n #def check_simple_2d(self):\n # \"\"\" result = a + b\"\"\" \n # expr = \"result = a + b\"\n # self.generic_2d(expr)\n def check_5point_avg_2d(self):\n \"\"\" result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\n + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n \"\"\" \n expr = \"result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n self.generic_2d(expr)\n \ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_ast_to_blitz_expr,'check_') )\n suites.append( unittest.makeSuite(test_blitz,'check_') ) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "methods": [ { "name": "generic_test", "long_name": "generic_test( self , expr , desired )", "filename": "test_blitz_tools.py", "nloc": 8, "complexity": 1, "token_count": 54, "parameters": [ "self", "expr", "desired" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "check_simple_expr", "long_name": "check_simple_expr( self )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 36, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "check_fdtd_expr", "long_name": "check_fdtd_expr( self )", "filename": "test_blitz_tools.py", "nloc": 14, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 46, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 21, "top_nesting_level": 1 }, { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 225, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "generic_2d", "long_name": "generic_2d( self , expr )", "filename": "test_blitz_tools.py", "nloc": 35, "complexity": 7, "token_count": 253, "parameters": [ "self", "expr" ], "start_line": 105, "end_line": 143, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "check_5point_avg_2d", "long_name": "check_5point_avg_2d( self )", "filename": "test_blitz_tools.py", "nloc": 4, "complexity": 1, "token_count": 17, "parameters": [ "self" ], "start_line": 148, "end_line": 154, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_blitz_tools.py", "nloc": 6, "complexity": 1, "token_count": 44, "parameters": [], "start_line": 156, "end_line": 161, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 163, "end_line": 167, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "methods_before": [ { "name": "generic_test", "long_name": "generic_test( self , expr , desired )", "filename": "test_blitz_tools.py", "nloc": 8, "complexity": 1, "token_count": 54, "parameters": [ "self", "expr", "desired" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "check_simple_expr", "long_name": "check_simple_expr( self )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 36, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "check_fdtd_expr", "long_name": "check_fdtd_expr( self )", "filename": "test_blitz_tools.py", "nloc": 14, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 46, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 21, "top_nesting_level": 1 }, { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 227, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "generic_2d", "long_name": "generic_2d( self , expr )", "filename": "test_blitz_tools.py", "nloc": 35, "complexity": 7, "token_count": 253, "parameters": [ "self", "expr" ], "start_line": 105, "end_line": 143, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "check_5point_avg_2d", "long_name": "check_5point_avg_2d( self )", "filename": "test_blitz_tools.py", "nloc": 4, "complexity": 1, "token_count": 17, "parameters": [ "self" ], "start_line": 148, "end_line": 154, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_blitz_tools.py", "nloc": 6, "complexity": 1, "token_count": 44, "parameters": [], "start_line": 156, "end_line": 161, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 163, "end_line": 167, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 225, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 } ], "nloc": 131, "complexity": 15, "token_count": 773, "diff_parsed": { "added": [ " blitz_tools.blitz(expr,arg_dict,{},verbose) #," ], "deleted": [ " blitz_tools.blitz(expr,arg_dict,{},verbose=2) #," ] } } ] }, { "hash": "9ac0623bd3d8c6534245039a0fcd262105492470", "msg": "slightly changed output from one test", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T18:39:33+00:00", "author_timezone": 0, "committer_date": "2002-01-17T18:39:33+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "5e9fe5d6a531bce42b13c88b8b3fb8b28de9b828" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 2, "lines": 3, "files": 1, "dmm_unit_size": 1.0, "dmm_unit_complexity": 1.0, "dmm_unit_interfacing": 1.0, "modified_files": [ { "old_path": "weave/tests/test_ext_tools.py", "new_path": "weave/tests/test_ext_tools.py", "filename": "test_ext_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -49,7 +49,8 @@ def check_with_include(self):\n # function 2 --> a little more complex expression\n var_specs = ext_tools.assign_variable_types(['a'],locals(),globals())\n code = \"\"\"\n- std::cout << \"a:\" << a << std::endl;\n+ std::cout << std::endl;\n+ std::cout << \"test printing a value:\" << a << std::endl;\n \"\"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n", "added_lines": 2, "deleted_lines": 1, "source_code": "import unittest\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path, restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport ext_tools\ntry:\n from standard_array_spec import array_specification\nexcept ImportError:\n pass # requires Numeric \nrestore_path()\n\nadd_local_to_path(__name__)\nfrom weave_test_utils import *\nrestore_path()\n\nbuild_dir = empty_temp_dir()\nprint 'building extensions here:', build_dir \n\nclass test_ext_module(unittest.TestCase):\n #should really do some testing of where modules end up\n def check_simple(self):\n \"\"\" Simplest possible module \"\"\"\n mod = ext_tools.ext_module('simple_ext_module')\n mod.compile(location = build_dir)\n import simple_ext_module\n def check_multi_functions(self):\n mod = ext_tools.ext_module('module_multi_function')\n var_specs = []\n code = \"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n test2 = ext_tools.ext_function_from_specs('test2',code,var_specs)\n mod.add_function(test2)\n mod.compile(location = build_dir)\n import module_multi_function\n module_multi_function.test()\n module_multi_function.test2()\n def check_with_include(self):\n # decalaring variables\n a = 2.;\n \n # declare module\n mod = ext_tools.ext_module('ext_module_with_include')\n mod.customize.add_header('')\n \n # function 2 --> a little more complex expression\n var_specs = ext_tools.assign_variable_types(['a'],locals(),globals())\n code = \"\"\"\n std::cout << std::endl;\n std::cout << \"test printing a value:\" << a << std::endl;\n \"\"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n # build module\n mod.compile(location = build_dir)\n import ext_module_with_include\n ext_module_with_include.test(a)\n\n def check_string_and_int(self): \n # decalaring variables\n a = 2;b = 'string' \n # declare module\n mod = ext_tools.ext_module('ext_string_and_int')\n code = \"\"\"\n a=b.length();\n return_val = Py::new_reference_to(Py::Int(a));\n \"\"\"\n test = ext_tools.ext_function('test',code,['a','b'])\n mod.add_function(test)\n mod.compile(location = build_dir)\n import ext_string_and_int\n c = ext_string_and_int.test(a,b)\n assert(c == len(b))\n \n def check_return_tuple(self): \n # decalaring variables\n a = 2 \n # declare module\n mod = ext_tools.ext_module('ext_return_tuple')\n var_specs = ext_tools.assign_variable_types(['a'],locals())\n code = \"\"\"\n int b;\n b = a + 1;\n Py::Tuple returned(2);\n returned[0] = Py::Int(a);\n returned[1] = Py::Int(b);\n return_val = Py::new_reference_to(returned);\n \"\"\"\n test = ext_tools.ext_function('test',code,['a'])\n mod.add_function(test)\n mod.compile(location = build_dir)\n import ext_return_tuple\n c,d = ext_return_tuple.test(a)\n assert(c==a and d == a+1)\n \nclass test_ext_function(unittest.TestCase):\n #should really do some testing of where modules end up\n def check_simple(self):\n \"\"\" Simplest possible function \"\"\"\n mod = ext_tools.ext_module('simple_ext_function')\n var_specs = []\n code = \"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n mod.compile(location = build_dir)\n import simple_ext_function\n simple_ext_function.test()\n \nclass test_assign_variable_types(unittest.TestCase): \n def check_assign_variable_types(self):\n try:\n from Numeric import arange, Float32, Float64\n except:\n # skip this test if Numeric not installed\n return\n \n import types\n a = arange(10,typecode = Float32)\n b = arange(5,typecode = Float64)\n c = 5\n arg_list = ['a','b','c']\n actual = ext_tools.assign_variable_types(arg_list,locals()) \n #desired = {'a':(Float32,1),'b':(Float32,1),'i':(Int32,0)}\n \n ad = array_specification()\n ad.name, ad.numeric_type, ad.dims = 'a', Float32, 1\n bd = array_specification()\n bd.name, bd.numeric_type, bd.dims = 'b', Float64, 1\n import scalar_spec\n cd = scalar_spec.int_specification()\n cd.name, cd.numeric_type = 'c', types.IntType \n desired = [ad,bd,cd]\n expr = \"\"\n print_assert_equal(expr,actual,desired)\n\n\ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_assign_variable_types,'check_') )\n suites.append( unittest.makeSuite(test_ext_module,'check_'))\n suites.append( unittest.makeSuite(test_ext_function,'check_')) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "source_code_before": "import unittest\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path, restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport ext_tools\ntry:\n from standard_array_spec import array_specification\nexcept ImportError:\n pass # requires Numeric \nrestore_path()\n\nadd_local_to_path(__name__)\nfrom weave_test_utils import *\nrestore_path()\n\nbuild_dir = empty_temp_dir()\nprint 'building extensions here:', build_dir \n\nclass test_ext_module(unittest.TestCase):\n #should really do some testing of where modules end up\n def check_simple(self):\n \"\"\" Simplest possible module \"\"\"\n mod = ext_tools.ext_module('simple_ext_module')\n mod.compile(location = build_dir)\n import simple_ext_module\n def check_multi_functions(self):\n mod = ext_tools.ext_module('module_multi_function')\n var_specs = []\n code = \"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n test2 = ext_tools.ext_function_from_specs('test2',code,var_specs)\n mod.add_function(test2)\n mod.compile(location = build_dir)\n import module_multi_function\n module_multi_function.test()\n module_multi_function.test2()\n def check_with_include(self):\n # decalaring variables\n a = 2.;\n \n # declare module\n mod = ext_tools.ext_module('ext_module_with_include')\n mod.customize.add_header('')\n \n # function 2 --> a little more complex expression\n var_specs = ext_tools.assign_variable_types(['a'],locals(),globals())\n code = \"\"\"\n std::cout << \"a:\" << a << std::endl;\n \"\"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n # build module\n mod.compile(location = build_dir)\n import ext_module_with_include\n ext_module_with_include.test(a)\n\n def check_string_and_int(self): \n # decalaring variables\n a = 2;b = 'string' \n # declare module\n mod = ext_tools.ext_module('ext_string_and_int')\n code = \"\"\"\n a=b.length();\n return_val = Py::new_reference_to(Py::Int(a));\n \"\"\"\n test = ext_tools.ext_function('test',code,['a','b'])\n mod.add_function(test)\n mod.compile(location = build_dir)\n import ext_string_and_int\n c = ext_string_and_int.test(a,b)\n assert(c == len(b))\n \n def check_return_tuple(self): \n # decalaring variables\n a = 2 \n # declare module\n mod = ext_tools.ext_module('ext_return_tuple')\n var_specs = ext_tools.assign_variable_types(['a'],locals())\n code = \"\"\"\n int b;\n b = a + 1;\n Py::Tuple returned(2);\n returned[0] = Py::Int(a);\n returned[1] = Py::Int(b);\n return_val = Py::new_reference_to(returned);\n \"\"\"\n test = ext_tools.ext_function('test',code,['a'])\n mod.add_function(test)\n mod.compile(location = build_dir)\n import ext_return_tuple\n c,d = ext_return_tuple.test(a)\n assert(c==a and d == a+1)\n \nclass test_ext_function(unittest.TestCase):\n #should really do some testing of where modules end up\n def check_simple(self):\n \"\"\" Simplest possible function \"\"\"\n mod = ext_tools.ext_module('simple_ext_function')\n var_specs = []\n code = \"\"\n test = ext_tools.ext_function_from_specs('test',code,var_specs)\n mod.add_function(test)\n mod.compile(location = build_dir)\n import simple_ext_function\n simple_ext_function.test()\n \nclass test_assign_variable_types(unittest.TestCase): \n def check_assign_variable_types(self):\n try:\n from Numeric import arange, Float32, Float64\n except:\n # skip this test if Numeric not installed\n return\n \n import types\n a = arange(10,typecode = Float32)\n b = arange(5,typecode = Float64)\n c = 5\n arg_list = ['a','b','c']\n actual = ext_tools.assign_variable_types(arg_list,locals()) \n #desired = {'a':(Float32,1),'b':(Float32,1),'i':(Int32,0)}\n \n ad = array_specification()\n ad.name, ad.numeric_type, ad.dims = 'a', Float32, 1\n bd = array_specification()\n bd.name, bd.numeric_type, bd.dims = 'b', Float64, 1\n import scalar_spec\n cd = scalar_spec.int_specification()\n cd.name, cd.numeric_type = 'c', types.IntType \n desired = [ad,bd,cd]\n expr = \"\"\n print_assert_equal(expr,actual,desired)\n\n\ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_assign_variable_types,'check_') )\n suites.append( unittest.makeSuite(test_ext_module,'check_'))\n suites.append( unittest.makeSuite(test_ext_function,'check_')) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "methods": [ { "name": "check_simple", "long_name": "check_simple( self )", "filename": "test_ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 24, "parameters": [ "self" ], "start_line": 24, "end_line": 28, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "check_multi_functions", "long_name": "check_multi_functions( self )", "filename": "test_ext_tools.py", "nloc": 12, "complexity": 1, "token_count": 76, "parameters": [ "self" ], "start_line": 29, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 1 }, { "name": "check_with_include", "long_name": "check_with_include( self )", "filename": "test_ext_tools.py", "nloc": 14, "complexity": 1, "token_count": 81, "parameters": [ "self" ], "start_line": 41, "end_line": 60, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 1 }, { "name": "check_string_and_int", "long_name": "check_string_and_int( self )", "filename": "test_ext_tools.py", "nloc": 13, "complexity": 1, "token_count": 74, "parameters": [ "self" ], "start_line": 62, "end_line": 76, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "check_return_tuple", "long_name": "check_return_tuple( self )", "filename": "test_ext_tools.py", "nloc": 18, "complexity": 2, "token_count": 85, "parameters": [ "self" ], "start_line": 78, "end_line": 97, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 1 }, { "name": "check_simple", "long_name": "check_simple( self )", "filename": "test_ext_tools.py", "nloc": 9, "complexity": 1, "token_count": 54, "parameters": [ "self" ], "start_line": 101, "end_line": 110, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "check_assign_variable_types", "long_name": "check_assign_variable_types( self )", "filename": "test_ext_tools.py", "nloc": 21, "complexity": 2, "token_count": 150, "parameters": [ "self" ], "start_line": 113, "end_line": 137, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_ext_tools.py", "nloc": 7, "complexity": 1, "token_count": 57, "parameters": [], "start_line": 140, "end_line": 146, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 148, "end_line": 152, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "methods_before": [ { "name": "check_simple", "long_name": "check_simple( self )", "filename": "test_ext_tools.py", "nloc": 4, "complexity": 1, "token_count": 24, "parameters": [ "self" ], "start_line": 24, "end_line": 28, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "check_multi_functions", "long_name": "check_multi_functions( self )", "filename": "test_ext_tools.py", "nloc": 12, "complexity": 1, "token_count": 76, "parameters": [ "self" ], "start_line": 29, "end_line": 40, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 1 }, { "name": "check_with_include", "long_name": "check_with_include( self )", "filename": "test_ext_tools.py", "nloc": 13, "complexity": 1, "token_count": 81, "parameters": [ "self" ], "start_line": 41, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 19, "top_nesting_level": 1 }, { "name": "check_string_and_int", "long_name": "check_string_and_int( self )", "filename": "test_ext_tools.py", "nloc": 13, "complexity": 1, "token_count": 74, "parameters": [ "self" ], "start_line": 61, "end_line": 75, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 1 }, { "name": "check_return_tuple", "long_name": "check_return_tuple( self )", "filename": "test_ext_tools.py", "nloc": 18, "complexity": 2, "token_count": 85, "parameters": [ "self" ], "start_line": 77, "end_line": 96, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 1 }, { "name": "check_simple", "long_name": "check_simple( self )", "filename": "test_ext_tools.py", "nloc": 9, "complexity": 1, "token_count": 54, "parameters": [ "self" ], "start_line": 100, "end_line": 109, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 10, "top_nesting_level": 1 }, { "name": "check_assign_variable_types", "long_name": "check_assign_variable_types( self )", "filename": "test_ext_tools.py", "nloc": 21, "complexity": 2, "token_count": 150, "parameters": [ "self" ], "start_line": 112, "end_line": 136, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_ext_tools.py", "nloc": 7, "complexity": 1, "token_count": 57, "parameters": [], "start_line": 139, "end_line": 145, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_ext_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 147, "end_line": 151, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "check_with_include", "long_name": "check_with_include( self )", "filename": "test_ext_tools.py", "nloc": 14, "complexity": 1, "token_count": 81, "parameters": [ "self" ], "start_line": 41, "end_line": 60, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 1 } ], "nloc": 124, "complexity": 11, "token_count": 723, "diff_parsed": { "added": [ " std::cout << std::endl;", " std::cout << \"test printing a value:\" << a << std::endl;" ], "deleted": [ " std::cout << \"a:\" << a << std::endl;" ] } } ] }, { "hash": "29583b16259c83099ea35467ea864f5e4a02c8b1", "msg": "fixed error introduced in last change", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-17T18:41:07+00:00", "author_timezone": 0, "committer_date": "2002-01-17T18:41:07+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "9ac0623bd3d8c6534245039a0fcd262105492470" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 1, "lines": 2, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/tests/test_blitz_tools.py", "new_path": "weave/tests/test_blitz_tools.py", "filename": "test_blitz_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -81,7 +81,7 @@ def generic_test(self,expr,arg_dict,type,size,mod_location):\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n- blitz_tools.blitz(expr,arg_dict,{},verbose) #,\n+ blitz_tools.blitz(expr,arg_dict,{},verbose=0) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n", "added_lines": 1, "deleted_lines": 1, "source_code": "import unittest\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \nimport RandomArray\nimport os\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path,restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport blitz_tools\nfrom ast_tools import *\nfrom weave_test_utils import *\nrestore_path()\n\nadd_local_to_path(__name__)\nimport test_scalar_spec\nrestore_path()\n\nclass test_ast_to_blitz_expr(unittest.TestCase):\n\n def generic_test(self,expr,desired):\n import parser\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n actual = blitz_tools.ast_to_blitz_expr(ast_list)\n actual = remove_whitespace(actual)\n desired = remove_whitespace(desired)\n print_assert_equal(expr,actual,desired)\n\n def check_simple_expr(self):\n \"\"\"convert simple expr to blitz\n \n a[:1:2] = b[:1+i+2:]\n \"\"\"\n expr = \"a[:1:2] = b[:1+i+2:]\" \n desired = \"a(blitz::Range(_beg,1-1,2))=\"\\\n \"b(blitz::Range(_beg,1+i+2-1));\"\n self.generic_test(expr,desired)\n\n def check_fdtd_expr(self):\n \"\"\" convert fdtd equation to blitz.\n ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] \n + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\n - cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1]);\n Note: This really should have \"\\\" at the end of each line\n to indicate continuation. \n \"\"\"\n expr = \"ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n desired = 'ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))='\\\n ' ca_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' *ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '+cb_y_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hz(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' -hz(_all,blitz::Range(_beg,_Nhz(1)-1-1),_all))'\\\n ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,_Nhy(2)-1-1)));'\n self.generic_test(expr,desired)\n\nclass test_blitz(unittest.TestCase):\n \"\"\"* These are long running tests...\n \n I'd like to benchmark these things somehow.\n *\"\"\"\n def generic_test(self,expr,arg_dict,type,size,mod_location):\n clean_result = array(arg_dict['result'],copy=1)\n t1 = time.time()\n exec expr in globals(),arg_dict\n t2 = time.time()\n standard = t2 - t1\n desired = arg_dict['result']\n arg_dict['result'] = clean_result\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n blitz_tools.blitz(expr,arg_dict,{},verbose=0) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n actual = arg_dict['result']\n # this really should give more info...\n try:\n # this isn't very stringent. Need to tighten this up and\n # learn where failures are occuring.\n assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))\n except:\n diff = actual-desired\n print diff[:4,:4]\n print diff[:4,-4:]\n print diff[-4:,:4]\n print diff[-4:,-4:]\n print sum(abs(diff.flat)) \n raise AssertionError \n return standard,compiled\n \n def generic_2d(self,expr):\n \"\"\" The complex testing is pretty lame...\n \"\"\"\n mod_location = empty_temp_dir()\n import parser\n ast = parser.suite(expr)\n arg_list = harvest_variables(ast.tolist())\n #print arg_list\n all_types = [Float32,Float64,Complex32,Complex64]\n all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)]\n print '\\nExpression:', expr\n for typ in all_types:\n for size in all_sizes:\n result = zeros(size,typ)\n arg_dict = {}\n for arg in arg_list:\n arg_dict[arg] = RandomArray.normal(0,1,size).astype(typ)\n arg_dict[arg].savespace(1)\n # set imag part of complex values to non-zero value\n try: arg_dict[arg].imag = arg_dict[arg].real\n except: pass \n print 'Run:', size,typ\n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1.\n print \"1st run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up) \n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1. \n print \"2nd run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up)\n cleanup_temp_dir(mod_location) \n #def check_simple_2d(self):\n # \"\"\" result = a + b\"\"\" \n # expr = \"result = a + b\"\n # self.generic_2d(expr)\n def check_5point_avg_2d(self):\n \"\"\" result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\n + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n \"\"\" \n expr = \"result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n self.generic_2d(expr)\n \ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_ast_to_blitz_expr,'check_') )\n suites.append( unittest.makeSuite(test_blitz,'check_') ) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "source_code_before": "import unittest\nfrom Numeric import *\n# The following try/except so that non-SciPy users can still use blitz\ntry:\n from fastumath import *\nexcept:\n pass # fastumath not available \nimport RandomArray\nimport os\nimport time\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path,restore_path\nfrom scipy_distutils.misc_util import add_local_to_path\n\nadd_grandparent_to_path(__name__)\nimport blitz_tools\nfrom ast_tools import *\nfrom weave_test_utils import *\nrestore_path()\n\nadd_local_to_path(__name__)\nimport test_scalar_spec\nrestore_path()\n\nclass test_ast_to_blitz_expr(unittest.TestCase):\n\n def generic_test(self,expr,desired):\n import parser\n ast = parser.suite(expr)\n ast_list = ast.tolist()\n actual = blitz_tools.ast_to_blitz_expr(ast_list)\n actual = remove_whitespace(actual)\n desired = remove_whitespace(desired)\n print_assert_equal(expr,actual,desired)\n\n def check_simple_expr(self):\n \"\"\"convert simple expr to blitz\n \n a[:1:2] = b[:1+i+2:]\n \"\"\"\n expr = \"a[:1:2] = b[:1+i+2:]\" \n desired = \"a(blitz::Range(_beg,1-1,2))=\"\\\n \"b(blitz::Range(_beg,1+i+2-1));\"\n self.generic_test(expr,desired)\n\n def check_fdtd_expr(self):\n \"\"\" convert fdtd equation to blitz.\n ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:] \n + cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\n - cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1]);\n Note: This really should have \"\\\" at the end of each line\n to indicate continuation. \n \"\"\"\n expr = \"ex[:,1:,1:] = ca_x[:,1:,1:] * ex[:,1:,1:]\" \\\n \"+ cb_y_x[:,1:,1:] * (hz[:,1:,1:] - hz[:,:-1,:])\"\\\n \"- cb_z_x[:,1:,1:] * (hy[:,1:,1:] - hy[:,1:,:-1])\" \n desired = 'ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))='\\\n ' ca_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' *ex(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '+cb_y_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hz(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n ' -hz(_all,blitz::Range(_beg,_Nhz(1)-1-1),_all))'\\\n ' -cb_z_x(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '*(hy(_all,blitz::Range(1,_end),blitz::Range(1,_end))'\\\n '-hy(_all,blitz::Range(1,_end),blitz::Range(_beg,_Nhy(2)-1-1)));'\n self.generic_test(expr,desired)\n\nclass test_blitz(unittest.TestCase):\n \"\"\"* These are long running tests...\n \n I'd like to benchmark these things somehow.\n *\"\"\"\n def generic_test(self,expr,arg_dict,type,size,mod_location):\n clean_result = array(arg_dict['result'],copy=1)\n t1 = time.time()\n exec expr in globals(),arg_dict\n t2 = time.time()\n standard = t2 - t1\n desired = arg_dict['result']\n arg_dict['result'] = clean_result\n t1 = time.time()\n old_env = os.environ.get('PYTHONCOMPILED','')\n os.environ['PYTHONCOMPILED'] = mod_location\n blitz_tools.blitz(expr,arg_dict,{},verbose) #,\n #extra_compile_args = ['-O3','-malign-double','-funroll-loops'])\n os.environ['PYTHONCOMPILED'] = old_env\n t2 = time.time()\n compiled = t2 - t1\n actual = arg_dict['result']\n # this really should give more info...\n try:\n # this isn't very stringent. Need to tighten this up and\n # learn where failures are occuring.\n assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))\n except:\n diff = actual-desired\n print diff[:4,:4]\n print diff[:4,-4:]\n print diff[-4:,:4]\n print diff[-4:,-4:]\n print sum(abs(diff.flat)) \n raise AssertionError \n return standard,compiled\n \n def generic_2d(self,expr):\n \"\"\" The complex testing is pretty lame...\n \"\"\"\n mod_location = empty_temp_dir()\n import parser\n ast = parser.suite(expr)\n arg_list = harvest_variables(ast.tolist())\n #print arg_list\n all_types = [Float32,Float64,Complex32,Complex64]\n all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)]\n print '\\nExpression:', expr\n for typ in all_types:\n for size in all_sizes:\n result = zeros(size,typ)\n arg_dict = {}\n for arg in arg_list:\n arg_dict[arg] = RandomArray.normal(0,1,size).astype(typ)\n arg_dict[arg].savespace(1)\n # set imag part of complex values to non-zero value\n try: arg_dict[arg].imag = arg_dict[arg].real\n except: pass \n print 'Run:', size,typ\n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1.\n print \"1st run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up) \n standard,compiled = self.generic_test(expr,arg_dict,type,size,\n mod_location)\n try:\n speed_up = standard/compiled\n except:\n speed_up = -1. \n print \"2nd run(Numeric,compiled,speed up): %3.4f, %3.4f, \" \\\n \"%3.4f\" % (standard,compiled,speed_up)\n cleanup_temp_dir(mod_location) \n #def check_simple_2d(self):\n # \"\"\" result = a + b\"\"\" \n # expr = \"result = a + b\"\n # self.generic_2d(expr)\n def check_5point_avg_2d(self):\n \"\"\" result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\n + b[1:-1,2:] + b[1:-1,:-2]) / 5.\n \"\"\" \n expr = \"result[1:-1,1:-1] = (b[1:-1,1:-1] + b[2:,1:-1] + b[:-2,1:-1]\" \\\n \"+ b[1:-1,2:] + b[1:-1,:-2]) / 5.\"\n self.generic_2d(expr)\n \ndef test_suite():\n suites = []\n suites.append( unittest.makeSuite(test_ast_to_blitz_expr,'check_') )\n suites.append( unittest.makeSuite(test_blitz,'check_') ) \n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "methods": [ { "name": "generic_test", "long_name": "generic_test( self , expr , desired )", "filename": "test_blitz_tools.py", "nloc": 8, "complexity": 1, "token_count": 54, "parameters": [ "self", "expr", "desired" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "check_simple_expr", "long_name": "check_simple_expr( self )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 36, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "check_fdtd_expr", "long_name": "check_fdtd_expr( self )", "filename": "test_blitz_tools.py", "nloc": 14, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 46, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 21, "top_nesting_level": 1 }, { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 227, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "generic_2d", "long_name": "generic_2d( self , expr )", "filename": "test_blitz_tools.py", "nloc": 35, "complexity": 7, "token_count": 253, "parameters": [ "self", "expr" ], "start_line": 105, "end_line": 143, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "check_5point_avg_2d", "long_name": "check_5point_avg_2d( self )", "filename": "test_blitz_tools.py", "nloc": 4, "complexity": 1, "token_count": 17, "parameters": [ "self" ], "start_line": 148, "end_line": 154, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_blitz_tools.py", "nloc": 6, "complexity": 1, "token_count": 44, "parameters": [], "start_line": 156, "end_line": 161, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 163, "end_line": 167, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "methods_before": [ { "name": "generic_test", "long_name": "generic_test( self , expr , desired )", "filename": "test_blitz_tools.py", "nloc": 8, "complexity": 1, "token_count": 54, "parameters": [ "self", "expr", "desired" ], "start_line": 27, "end_line": 34, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 8, "top_nesting_level": 1 }, { "name": "check_simple_expr", "long_name": "check_simple_expr( self )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 22, "parameters": [ "self" ], "start_line": 36, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 9, "top_nesting_level": 1 }, { "name": "check_fdtd_expr", "long_name": "check_fdtd_expr( self )", "filename": "test_blitz_tools.py", "nloc": 14, "complexity": 1, "token_count": 40, "parameters": [ "self" ], "start_line": 46, "end_line": 66, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 21, "top_nesting_level": 1 }, { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 225, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 }, { "name": "generic_2d", "long_name": "generic_2d( self , expr )", "filename": "test_blitz_tools.py", "nloc": 35, "complexity": 7, "token_count": 253, "parameters": [ "self", "expr" ], "start_line": 105, "end_line": 143, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 39, "top_nesting_level": 1 }, { "name": "check_5point_avg_2d", "long_name": "check_5point_avg_2d( self )", "filename": "test_blitz_tools.py", "nloc": 4, "complexity": 1, "token_count": 17, "parameters": [ "self" ], "start_line": 148, "end_line": 154, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_blitz_tools.py", "nloc": 6, "complexity": 1, "token_count": 44, "parameters": [], "start_line": 156, "end_line": 161, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_blitz_tools.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 163, "end_line": 167, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "generic_test", "long_name": "generic_test( self , expr , arg_dict , type , size , mod_location )", "filename": "test_blitz_tools.py", "nloc": 27, "complexity": 2, "token_count": 227, "parameters": [ "self", "expr", "arg_dict", "type", "size", "mod_location" ], "start_line": 73, "end_line": 103, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 31, "top_nesting_level": 1 } ], "nloc": 131, "complexity": 15, "token_count": 775, "diff_parsed": { "added": [ " blitz_tools.blitz(expr,arg_dict,{},verbose=0) #," ], "deleted": [ " blitz_tools.blitz(expr,arg_dict,{},verbose) #," ] } } ] }, { "hash": "5ad4488c291c491b2ca6de659d9f9c846648f9b5", "msg": "converted array conversion checks to use classes so that we wouldn't get the dreaded Abort that occurs with exceptions in functions. This is silly, but it works.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-19T03:38:01+00:00", "author_timezone": 0, "committer_date": "2002-01-19T03:38:01+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "29583b16259c83099ea35467ea864f5e4a02c8b1" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 65, "insertions": 91, "lines": 156, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/standard_array_info.py", "new_path": "weave/standard_array_info.py", "filename": "standard_array_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -6,90 +6,116 @@\n \n array_convert_code = \\\n \"\"\"\n-static PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)\n-{\n- PyArrayObject* arr_obj = NULL;\n-\n- if (!py_obj || !PyArray_Check(py_obj))\n- handle_conversion_error(py_obj,\"array\", name);\n-\n- // Any need to deal with INC/DEC REFs?\n- Py_INCREF(py_obj);\n- return (PyArrayObject*) py_obj;\n-}\n \n-static PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)\n+class numpy_handler\n {\n- PyArrayObject* arr_obj = NULL;\n-\n- if (!py_obj || !PyArray_Check(py_obj))\n- handle_bad_type(py_obj,\"array\", name);\n-\n- // Any need to deal with INC/DEC REFs?\n- Py_INCREF(py_obj);\n- return (PyArrayObject*) py_obj;\n-}\n+public:\n+ PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)\n+ {\n+ PyArrayObject* arr_obj = NULL;\n+ \n+ if (!py_obj || !PyArray_Check(py_obj))\n+ handle_conversion_error(py_obj,\"array\", name);\n+ \n+ // Any need to deal with INC/DEC REFs?\n+ Py_INCREF(py_obj);\n+ return (PyArrayObject*) py_obj;\n+ }\n+ \n+ PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)\n+ {\n+ PyArrayObject* arr_obj = NULL;\n+ \n+ if (!py_obj || !PyArray_Check(py_obj))\n+ handle_bad_type(py_obj,\"array\", name);\n+ \n+ // Any need to deal with INC/DEC REFs?\n+ Py_INCREF(py_obj);\n+ return (PyArrayObject*) py_obj;\n+ }\n+};\n \n+numpy_handler x__numpy_handler = numpy_handler();\n+#define convert_to_numpy x__numpy_handler.convert_to_numpy\n+#define convert_to_numpy x__numpy_handler.py_to_numpy\n \"\"\"\n \n type_check_code = \\\n \"\"\"\n-void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,\n- const char* name)\n+class numpy_type_handler\n {\n- // Make sure input has correct numeric type.\n- if (arr_obj->descr->type_num != numeric_type)\n+public:\n+ void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,\n+ const char* name)\n {\n- char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n- \"long\", \"float\", \"double\", \"complex float\",\n- \"complex double\", \"object\",\"ntype\",\"unkown\"};\n- char msg[500];\n- sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n- type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n- throw_error(PyExc_TypeError,msg); \n+ // Make sure input has correct numeric type.\n+ if (arr_obj->descr->type_num != numeric_type)\n+ {\n+ char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n+ \"long\", \"float\", \"double\", \"complex float\",\n+ \"complex double\", \"object\",\"ntype\",\"unkown\"};\n+ char msg[500];\n+ sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n+ type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n+ throw_error(PyExc_TypeError,msg); \n+ }\n }\n-}\n-\n-void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)\n-{\n- // Make sure input has correct numeric type.\n- if (arr_obj->descr->type_num != numeric_type)\n+ \n+ void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)\n {\n- char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n- \"long\", \"float\", \"double\", \"complex float\",\n- \"complex double\", \"object\",\"ntype\",\"unkown\"};\n- char msg[500];\n- sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n- type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n- throw_error(PyExc_TypeError,msg); \n+ // Make sure input has correct numeric type.\n+ if (arr_obj->descr->type_num != numeric_type)\n+ {\n+ char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n+ \"long\", \"float\", \"double\", \"complex float\",\n+ \"complex double\", \"object\",\"ntype\",\"unkown\"};\n+ char msg[500];\n+ sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n+ type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n+ throw_error(PyExc_TypeError,msg); \n+ }\n }\n-}\n+};\n+\n+numpy_type_handler x__numpy_type_handler = numpy_type_handler();\n+#define conversion_numpy_check_type x__numpy_type_handler.conversion_numpy_check_type\n+#define numpy_check_type x__numpy_type_handler.numpy_check_type\n+\n \"\"\"\n \n size_check_code = \\\n \"\"\"\n-void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, \n- const char* name)\n+class numpy_size_handler\n {\n- if (arr_obj->nd != Ndims)\n+public:\n+ void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, \n+ const char* name)\n {\n- char msg[500];\n- sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n- arr_obj->nd,Ndims,name);\n- throw_error(PyExc_TypeError,msg);\n- } \n-}\n-\n-void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)\n-{\n- if (arr_obj->nd != Ndims)\n+ if (arr_obj->nd != Ndims)\n+ {\n+ char msg[500];\n+ sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n+ arr_obj->nd,Ndims,name);\n+ throw_error(PyExc_TypeError,msg);\n+ } \n+ }\n+ \n+ void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)\n {\n- char msg[500];\n- sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n- arr_obj->nd,Ndims,name);\n- throw_error(PyExc_TypeError,msg);\n- } \n-}\n+ if (arr_obj->nd != Ndims)\n+ {\n+ char msg[500];\n+ sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n+ arr_obj->nd,Ndims,name);\n+ throw_error(PyExc_TypeError,msg);\n+ } \n+ }\n+};\n+\n+numpy_size_handler x__numpy_size_handler = numpy_size_handler();\n+#define conversion_numpy_check_size x__numpy_size_handler.conversion_numpy_check_size\n+#define numpy_check_size x__numpy_size_handler.numpy_check_size\n+\n \"\"\"\n \n numeric_init_code = \\\n", "added_lines": 91, "deleted_lines": 65, "source_code": "\"\"\" Generic support code for handling standard Numeric arrays \n\"\"\"\n\nimport base_info\n\n\narray_convert_code = \\\n\"\"\"\n\nclass numpy_handler\n{\npublic:\n PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)\n {\n PyArrayObject* arr_obj = NULL;\n \n if (!py_obj || !PyArray_Check(py_obj))\n handle_conversion_error(py_obj,\"array\", name);\n \n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n }\n \n PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)\n {\n PyArrayObject* arr_obj = NULL;\n \n if (!py_obj || !PyArray_Check(py_obj))\n handle_bad_type(py_obj,\"array\", name);\n \n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n }\n};\n\nnumpy_handler x__numpy_handler = numpy_handler();\n#define convert_to_numpy x__numpy_handler.convert_to_numpy\n#define convert_to_numpy x__numpy_handler.py_to_numpy\n\"\"\"\n\ntype_check_code = \\\n\"\"\"\nclass numpy_type_handler\n{\npublic:\n void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,\n const char* name)\n {\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n }\n \n void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)\n {\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n }\n};\n\nnumpy_type_handler x__numpy_type_handler = numpy_type_handler();\n#define conversion_numpy_check_type x__numpy_type_handler.conversion_numpy_check_type\n#define numpy_check_type x__numpy_type_handler.numpy_check_type\n\n\"\"\"\n\nsize_check_code = \\\n\"\"\"\nclass numpy_size_handler\n{\npublic:\n void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, \n const char* name)\n {\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n }\n \n void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)\n {\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n }\n};\n\nnumpy_size_handler x__numpy_size_handler = numpy_size_handler();\n#define conversion_numpy_check_size x__numpy_size_handler.conversion_numpy_check_size\n#define numpy_check_size x__numpy_size_handler.numpy_check_size\n\n\"\"\"\n\nnumeric_init_code = \\\n\"\"\"\nPy_Initialize();\nimport_array();\nPyImport_ImportModule(\"Numeric\");\n\"\"\"\n\nclass array_info(base_info.base_info):\n _headers = ['\"Numeric/arrayobject.h\"','','']\n _support_code = [array_convert_code,size_check_code, type_check_code]\n _module_init_code = [numeric_init_code] ", "source_code_before": "\"\"\" Generic support code for handling standard Numeric arrays \n\"\"\"\n\nimport base_info\n\n\narray_convert_code = \\\n\"\"\"\nstatic PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_conversion_error(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\nstatic PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)\n{\n PyArrayObject* arr_obj = NULL;\n\n if (!py_obj || !PyArray_Check(py_obj))\n handle_bad_type(py_obj,\"array\", name);\n\n // Any need to deal with INC/DEC REFs?\n Py_INCREF(py_obj);\n return (PyArrayObject*) py_obj;\n}\n\n\"\"\"\n\ntype_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,\n const char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\nvoid numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)\n{\n // Make sure input has correct numeric type.\n if (arr_obj->descr->type_num != numeric_type)\n {\n char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\", \n \"long\", \"float\", \"double\", \"complex float\",\n \"complex double\", \"object\",\"ntype\",\"unkown\"};\n char msg[500];\n sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",\n type_names[arr_obj->descr->type_num],type_names[numeric_type],name);\n throw_error(PyExc_TypeError,msg); \n }\n}\n\"\"\"\n\nsize_check_code = \\\n\"\"\"\nvoid conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims, \n const char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\nvoid numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)\n{\n if (arr_obj->nd != Ndims)\n {\n char msg[500];\n sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",\n arr_obj->nd,Ndims,name);\n throw_error(PyExc_TypeError,msg);\n } \n}\n\"\"\"\n\nnumeric_init_code = \\\n\"\"\"\nPy_Initialize();\nimport_array();\nPyImport_ImportModule(\"Numeric\");\n\"\"\"\n\nclass array_info(base_info.base_info):\n _headers = ['\"Numeric/arrayobject.h\"','','']\n _support_code = [array_convert_code,size_check_code, type_check_code]\n _module_init_code = [numeric_init_code] ", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 124, "complexity": 0, "token_count": 50, "diff_parsed": { "added": [ "class numpy_handler", "public:", " PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)", " {", " PyArrayObject* arr_obj = NULL;", "", " if (!py_obj || !PyArray_Check(py_obj))", " handle_conversion_error(py_obj,\"array\", name);", "", " // Any need to deal with INC/DEC REFs?", " Py_INCREF(py_obj);", " return (PyArrayObject*) py_obj;", " }", "", " PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)", " {", " PyArrayObject* arr_obj = NULL;", "", " if (!py_obj || !PyArray_Check(py_obj))", " handle_bad_type(py_obj,\"array\", name);", "", " // Any need to deal with INC/DEC REFs?", " Py_INCREF(py_obj);", " return (PyArrayObject*) py_obj;", " }", "};", "numpy_handler x__numpy_handler = numpy_handler();", "#define convert_to_numpy x__numpy_handler.convert_to_numpy", "#define convert_to_numpy x__numpy_handler.py_to_numpy", "class numpy_type_handler", "public:", " void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,", " const char* name)", " // Make sure input has correct numeric type.", " if (arr_obj->descr->type_num != numeric_type)", " {", " char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\",", " \"long\", \"float\", \"double\", \"complex float\",", " \"complex double\", \"object\",\"ntype\",\"unkown\"};", " char msg[500];", " sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",", " type_names[arr_obj->descr->type_num],type_names[numeric_type],name);", " throw_error(PyExc_TypeError,msg);", " }", "", " void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)", " // Make sure input has correct numeric type.", " if (arr_obj->descr->type_num != numeric_type)", " {", " char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\",", " \"long\", \"float\", \"double\", \"complex float\",", " \"complex double\", \"object\",\"ntype\",\"unkown\"};", " char msg[500];", " sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",", " type_names[arr_obj->descr->type_num],type_names[numeric_type],name);", " throw_error(PyExc_TypeError,msg);", " }", "};", "", "numpy_type_handler x__numpy_type_handler = numpy_type_handler();", "#define conversion_numpy_check_type x__numpy_type_handler.conversion_numpy_check_type", "#define numpy_check_type x__numpy_type_handler.numpy_check_type", "", "class numpy_size_handler", "public:", " void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims,", " const char* name)", " if (arr_obj->nd != Ndims)", " {", " char msg[500];", " sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",", " arr_obj->nd,Ndims,name);", " throw_error(PyExc_TypeError,msg);", " }", " }", "", " void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)", " if (arr_obj->nd != Ndims)", " {", " char msg[500];", " sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",", " arr_obj->nd,Ndims,name);", " throw_error(PyExc_TypeError,msg);", " }", " }", "};", "", "numpy_size_handler x__numpy_size_handler = numpy_size_handler();", "#define conversion_numpy_check_size x__numpy_size_handler.conversion_numpy_check_size", "#define numpy_check_size x__numpy_size_handler.numpy_check_size", "" ], "deleted": [ "static PyArrayObject* convert_to_numpy(PyObject* py_obj, const char* name)", "{", " PyArrayObject* arr_obj = NULL;", "", " if (!py_obj || !PyArray_Check(py_obj))", " handle_conversion_error(py_obj,\"array\", name);", "", " // Any need to deal with INC/DEC REFs?", " Py_INCREF(py_obj);", " return (PyArrayObject*) py_obj;", "}", "static PyArrayObject* py_to_numpy(PyObject* py_obj, const char* name)", " PyArrayObject* arr_obj = NULL;", "", " if (!py_obj || !PyArray_Check(py_obj))", " handle_bad_type(py_obj,\"array\", name);", "", " // Any need to deal with INC/DEC REFs?", " Py_INCREF(py_obj);", " return (PyArrayObject*) py_obj;", "}", "void conversion_numpy_check_type(PyArrayObject* arr_obj, int numeric_type,", " const char* name)", " // Make sure input has correct numeric type.", " if (arr_obj->descr->type_num != numeric_type)", " char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\",", " \"long\", \"float\", \"double\", \"complex float\",", " \"complex double\", \"object\",\"ntype\",\"unkown\"};", " char msg[500];", " sprintf(msg,\"Conversion Error: received '%s' typed array instead of '%s' typed array for variable '%s'\",", " type_names[arr_obj->descr->type_num],type_names[numeric_type],name);", " throw_error(PyExc_TypeError,msg);", "}", "", "void numpy_check_type(PyArrayObject* arr_obj, int numeric_type, const char* name)", "{", " // Make sure input has correct numeric type.", " if (arr_obj->descr->type_num != numeric_type)", " char* type_names[13] = {\"char\",\"unsigned byte\",\"byte\", \"short\", \"int\",", " \"long\", \"float\", \"double\", \"complex float\",", " \"complex double\", \"object\",\"ntype\",\"unkown\"};", " char msg[500];", " sprintf(msg,\"received '%s' typed array instead of '%s' typed array for variable '%s'\",", " type_names[arr_obj->descr->type_num],type_names[numeric_type],name);", " throw_error(PyExc_TypeError,msg);", "}", "void conversion_numpy_check_size(PyArrayObject* arr_obj, int Ndims,", " const char* name)", " if (arr_obj->nd != Ndims)", " char msg[500];", " sprintf(msg,\"Conversion Error: received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",", " arr_obj->nd,Ndims,name);", " throw_error(PyExc_TypeError,msg);", " }", "}", "", "void numpy_check_size(PyArrayObject* arr_obj, int Ndims, const char* name)", "{", " if (arr_obj->nd != Ndims)", " char msg[500];", " sprintf(msg,\"received '%d' dimensional array instead of '%d' dimensional array for variable '%s'\",", " arr_obj->nd,Ndims,name);", " throw_error(PyExc_TypeError,msg);", " }", "}" ] } } ] }, { "hash": "dccec0d0a632fa8e33df1a92c5dd382e6519c9cb", "msg": "a few (broken) fixes for blitz. Still in progress", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-19T04:40:11+00:00", "author_timezone": 0, "committer_date": "2002-01-19T04:40:11+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "5ad4488c291c491b2ca6de659d9f9c846648f9b5" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 16, "insertions": 42, "lines": 58, "files": 2, "dmm_unit_size": 0.0, "dmm_unit_complexity": 1.0, "dmm_unit_interfacing": 1.0, "modified_files": [ { "old_path": "weave/blitz_info.py", "new_path": "weave/blitz_info.py", "filename": "blitz_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -36,12 +36,13 @@ class py_type >{public: enum { code = PyArray_CFLOAT};};\n class py_type >{public: enum { code = PyArray_CDOUBLE};};\n \n template\n-static blitz::Array convert_to_blitz(PyObject* py_obj,const char* name)\n+static blitz::Array convert_to_blitz(PyArrayObject* py_obj,const char* name)\n {\n \n- PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n- conversion_numpy_check_size(arr_obj,N,name);\n- conversion_numpy_check_type(arr_obj,py_type::code,name);\n+ //This is now handled externally (for now) to deal with exception/Abort issue\n+ //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n+ //conversion_numpy_check_size(arr_obj,N,name);\n+ //conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n@@ -58,12 +59,12 @@ class py_type >{public: enum { code = PyArray_CDOUBLE};};\n }\n \n template\n-static blitz::Array py_to_blitz(PyObject* py_obj,const char* name)\n+static blitz::Array py_to_blitz(PyArrayObject* py_obj,const char* name)\n {\n-\n- PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n- numpy_check_size(arr_obj,N,name);\n- numpy_check_type(arr_obj,py_type::code,name);\n+ //This is now handled externally (for now) to deal with exception/Abort issue\n+ //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n+ //numpy_check_size(arr_obj,N,name);\n+ //numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n", "added_lines": 10, "deleted_lines": 9, "source_code": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyArrayObject* py_obj,const char* name)\n{\n\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n //conversion_numpy_check_size(arr_obj,N,name);\n //conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyArrayObject* py_obj,const char* name)\n{\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n //numpy_check_size(arr_obj,N,name);\n //numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "source_code_before": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyObject* py_obj,const char* name)\n{\n\n PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n conversion_numpy_check_size(arr_obj,N,name);\n conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyObject* py_obj,const char* name)\n{\n\n PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n numpy_check_size(arr_obj,N,name);\n numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "methods": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 102, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "methods_before": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 101, "end_line": 106, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "changed_methods": [], "nloc": 98, "complexity": 2, "token_count": 120, "diff_parsed": { "added": [ "static blitz::Array convert_to_blitz(PyArrayObject* py_obj,const char* name)", " //This is now handled externally (for now) to deal with exception/Abort issue", " //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);", " //conversion_numpy_check_size(arr_obj,N,name);", " //conversion_numpy_check_type(arr_obj,py_type::code,name);", "static blitz::Array py_to_blitz(PyArrayObject* py_obj,const char* name)", " //This is now handled externally (for now) to deal with exception/Abort issue", " //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);", " //numpy_check_size(arr_obj,N,name);", " //numpy_check_type(arr_obj,py_type::code,name);" ], "deleted": [ "static blitz::Array convert_to_blitz(PyObject* py_obj,const char* name)", " PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);", " conversion_numpy_check_size(arr_obj,N,name);", " conversion_numpy_check_type(arr_obj,py_type::code,name);", "static blitz::Array py_to_blitz(PyObject* py_obj,const char* name)", "", " PyArrayObject* arr_obj = py_to_numpy(py_obj,name);", " numpy_check_size(arr_obj,N,name);", " numpy_check_type(arr_obj,py_type::code,name);" ] } }, { "old_path": "weave/blitz_spec.py", "new_path": "weave/blitz_spec.py", "filename": "blitz_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -7,7 +7,7 @@\n \n class array_specification(base_specification):\n _build_information = [blitz_info.array_info()]\n- \n+\n def type_match(self,value):\n return type(value) is ArrayType\n \n@@ -29,34 +29,59 @@ def declaration_code(self,templatize = 0,inline=0):\n else:\n code = self.standard_decl_code()\n return code\n- \n+\n def inline_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=1)\n+ arr_name = name + '_arr_obj'\n+ # We've had to inject quite a bit of code in here to handle the Aborted error\n+ # caused by exceptions. The templates made the easy fix (with MACROS) for all\n+ # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'py_%(name)s= %(var_name)s;\\n' \\\n+ 'PyArrayObject* %(arr_name)s = convert_to_numpy(py_%(name)s,\"%(name)s\");\\n' \\\n+ 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);\\n' \\\n+ 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n+ # old version\n+ #templ = '// blitz_array_declaration\\n' \\\n+ # 'py_%(name)s= %(var_name)s;\\n' \\\n+ # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n+ # ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n+ # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n \n- def standard_decl_code(self): \n+ def standard_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=0)\n+ arr_name = name + '_arr_obj'\n+ # We've had to inject quite a bit of code in here to handle the Aborted error\n+ # caused by exceptions. The templates made the easy fix (with MACROS) for all\n+ # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n+ 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");' \\\n+ 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);' \\\n+ 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n- ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\\n+ ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n+ # old version\n+ #templ = '// blitz_array_declaration\\n' \\\n+ # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n+ # ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\\n+ # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n #def c_function_declaration_code(self):\n # \"\"\"\n- # This doesn't pass the size through. That info is gonna have to \n+ # This doesn't pass the size through. That info is gonna have to\n # be redone in the c function.\n # \"\"\"\n # templ_dict = {}\n@@ -65,10 +90,10 @@ def standard_decl_code(self):\n # templ_dict['name'] = self.name\n # code = 'blitz::Array<%(type)s,%(dims)d> &%(name)s' % templ_dict\n # return code\n- \n+\n def local_dict_code(self):\n code = '// for now, array \"%s\" is not returned as arryas are edited' \\\n- ' in place (should this change?)\\n' % (self.name) \n+ ' in place (should this change?)\\n' % (self.name)\n return code\n \n def cleanup_code(self):\n", "added_lines": 32, "deleted_lines": 7, "source_code": "from base_spec import base_specification\nfrom scalar_spec import numeric_to_blitz_type_mapping\nfrom Numeric import *\nfrom types import *\nimport os\nimport blitz_info\n\nclass array_specification(base_specification):\n _build_information = [blitz_info.array_info()]\n\n def type_match(self,value):\n return type(value) is ArrayType\n\n def type_spec(self,name,value):\n # factory\n new_spec = array_specification()\n new_spec.name = name\n new_spec.numeric_type = value.typecode()\n new_spec.dims = len(value.shape)\n if new_spec.dims > 11:\n msg = \"Error converting variable '\" + name + \"'. \" \\\n \"blitz only supports arrays up to 11 dimensions.\"\n raise ValueError, msg\n return new_spec\n\n def declaration_code(self,templatize = 0,inline=0):\n if inline:\n code = self.inline_decl_code()\n else:\n code = self.standard_decl_code()\n return code\n\n def inline_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=1)\n arr_name = name + '_arr_obj'\n # We've had to inject quite a bit of code in here to handle the Aborted error\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'py_%(name)s= %(var_name)s;\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(py_%(name)s,\"%(name)s\");\\n' \\\n 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);\\n' \\\n 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n # 'py_%(name)s= %(var_name)s;\\n' \\\n # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n # ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n\n def standard_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=0)\n arr_name = name + '_arr_obj'\n # We've had to inject quite a bit of code in here to handle the Aborted error\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");' \\\n 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);' \\\n 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n # ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\\n # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n #def c_function_declaration_code(self):\n # \"\"\"\n # This doesn't pass the size through. That info is gonna have to\n # be redone in the c function.\n # \"\"\"\n # templ_dict = {}\n # templ_dict['type'] = numeric_to_blitz_type_mapping[self.numeric_type]\n # templ_dict['dims'] = self.dims\n # templ_dict['name'] = self.name\n # code = 'blitz::Array<%(type)s,%(dims)d> &%(name)s' % templ_dict\n # return code\n\n def local_dict_code(self):\n code = '// for now, array \"%s\" is not returned as arryas are edited' \\\n ' in place (should this change?)\\n' % (self.name)\n return code\n\n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\n def __repr__(self):\n msg = \"(array:: name: %s, type: %s, dims: %d)\" % \\\n (self.name, self.numeric_type, self.dims)\n return msg\n\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.dims, other.dims) or \\\n cmp(self.__class__, other.__class__)\n\n# stick this factory on the front of the type factories\nimport ext_tools\nblitz_aware_factories = [array_specification()] + ext_tools.default_type_factories\n", "source_code_before": "from base_spec import base_specification\nfrom scalar_spec import numeric_to_blitz_type_mapping\nfrom Numeric import *\nfrom types import *\nimport os\nimport blitz_info\n\nclass array_specification(base_specification):\n _build_information = [blitz_info.array_info()]\n \n def type_match(self,value):\n return type(value) is ArrayType\n\n def type_spec(self,name,value):\n # factory\n new_spec = array_specification()\n new_spec.name = name\n new_spec.numeric_type = value.typecode()\n new_spec.dims = len(value.shape)\n if new_spec.dims > 11:\n msg = \"Error converting variable '\" + name + \"'. \" \\\n \"blitz only supports arrays up to 11 dimensions.\"\n raise ValueError, msg\n return new_spec\n\n def declaration_code(self,templatize = 0,inline=0):\n if inline:\n code = self.inline_decl_code()\n else:\n code = self.standard_decl_code()\n return code\n \n def inline_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=1)\n templ = '// blitz_array_declaration\\n' \\\n 'py_%(name)s= %(var_name)s;\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n\n def standard_decl_code(self): \n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=0)\n templ = '// blitz_array_declaration\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n #def c_function_declaration_code(self):\n # \"\"\"\n # This doesn't pass the size through. That info is gonna have to \n # be redone in the c function.\n # \"\"\"\n # templ_dict = {}\n # templ_dict['type'] = numeric_to_blitz_type_mapping[self.numeric_type]\n # templ_dict['dims'] = self.dims\n # templ_dict['name'] = self.name\n # code = 'blitz::Array<%(type)s,%(dims)d> &%(name)s' % templ_dict\n # return code\n \n def local_dict_code(self):\n code = '// for now, array \"%s\" is not returned as arryas are edited' \\\n ' in place (should this change?)\\n' % (self.name) \n return code\n\n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\n def __repr__(self):\n msg = \"(array:: name: %s, type: %s, dims: %d)\" % \\\n (self.name, self.numeric_type, self.dims)\n return msg\n\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.dims, other.dims) or \\\n cmp(self.__class__, other.__class__)\n\n# stick this factory on the front of the type factories\nimport ext_tools\nblitz_aware_factories = [array_specification()] + ext_tools.default_type_factories\n", "methods": [ { "name": "type_match", "long_name": "type_match( self , value )", "filename": "blitz_spec.py", "nloc": 2, "complexity": 1, "token_count": 14, "parameters": [ "self", "value" ], "start_line": 11, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "blitz_spec.py", "nloc": 10, "complexity": 2, "token_count": 60, "parameters": [ "self", "name", "value" ], "start_line": 14, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "blitz_spec.py", "nloc": 6, "complexity": 2, "token_count": 34, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 31, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "inline_decl_code", "long_name": "inline_decl_code( self )", "filename": "blitz_spec.py", "nloc": 16, "complexity": 1, "token_count": 64, "parameters": [ "self" ], "start_line": 33, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "standard_decl_code", "long_name": "standard_decl_code( self )", "filename": "blitz_spec.py", "nloc": 15, "complexity": 1, "token_count": 62, "parameters": [ "self" ], "start_line": 59, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 94, "end_line": 97, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "blitz_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 99, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 104, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "blitz_spec.py", "nloc": 5, "complexity": 4, "token_count": 54, "parameters": [ "self", "other" ], "start_line": 109, "end_line": 114, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "methods_before": [ { "name": "type_match", "long_name": "type_match( self , value )", "filename": "blitz_spec.py", "nloc": 2, "complexity": 1, "token_count": 14, "parameters": [ "self", "value" ], "start_line": 11, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "blitz_spec.py", "nloc": 10, "complexity": 2, "token_count": 60, "parameters": [ "self", "name", "value" ], "start_line": 14, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "blitz_spec.py", "nloc": 6, "complexity": 2, "token_count": 34, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 31, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "inline_decl_code", "long_name": "inline_decl_code( self )", "filename": "blitz_spec.py", "nloc": 12, "complexity": 1, "token_count": 53, "parameters": [ "self" ], "start_line": 33, "end_line": 44, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 12, "top_nesting_level": 1 }, { "name": "standard_decl_code", "long_name": "standard_decl_code( self )", "filename": "blitz_spec.py", "nloc": 11, "complexity": 1, "token_count": 51, "parameters": [ "self" ], "start_line": 46, "end_line": 56, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 69, "end_line": 72, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "blitz_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 74, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 79, "end_line": 82, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "blitz_spec.py", "nloc": 5, "complexity": 4, "token_count": 54, "parameters": [ "self", "other" ], "start_line": 84, "end_line": 89, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "changed_methods": [ { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 94, "end_line": 97, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "inline_decl_code", "long_name": "inline_decl_code( self )", "filename": "blitz_spec.py", "nloc": 16, "complexity": 1, "token_count": 64, "parameters": [ "self" ], "start_line": 33, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "standard_decl_code", "long_name": "standard_decl_code( self )", "filename": "blitz_spec.py", "nloc": 15, "complexity": 1, "token_count": 62, "parameters": [ "self" ], "start_line": 59, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 } ], "nloc": 75, "complexity": 14, "token_count": 402, "diff_parsed": { "added": [ "", "", " arr_name = name + '_arr_obj'", " # We've had to inject quite a bit of code in here to handle the Aborted error", " # caused by exceptions. The templates made the easy fix (with MACROS) for all", " # other types difficult here. Oh well.", " 'PyArrayObject* %(arr_name)s = convert_to_numpy(py_%(name)s,\"%(name)s\");\\n' \\", " 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);\\n' \\", " 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)\\n' \\", " # old version", " #templ = '// blitz_array_declaration\\n' \\", " # 'py_%(name)s= %(var_name)s;\\n' \\", " # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\", " # ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\", " # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'", " def standard_decl_code(self):", " arr_name = name + '_arr_obj'", " # We've had to inject quite a bit of code in here to handle the Aborted error", " # caused by exceptions. The templates made the easy fix (with MACROS) for all", " # other types difficult here. Oh well.", " 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");' \\", " 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);' \\", " 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)' \\", " ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\", " # old version", " #templ = '// blitz_array_declaration\\n' \\", " # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\", " # ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\", " # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'", " # This doesn't pass the size through. That info is gonna have to", "", " ' in place (should this change?)\\n' % (self.name)" ], "deleted": [ "", "", " def standard_decl_code(self):", " ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\", " # This doesn't pass the size through. That info is gonna have to", "", " ' in place (should this change?)\\n' % (self.name)" ] } } ] }, { "hash": "a38603fb8206a6da4a6dd68d85958892ed5e3631", "msg": "conversion of blitz stuff to handle Aborted completed. Had to mess with some code I didn't want to because of template issues, but that is the breaks.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-19T04:58:51+00:00", "author_timezone": 0, "committer_date": "2002-01-19T04:58:51+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "dccec0d0a632fa8e33df1a92c5dd382e6519c9cb" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 8, "insertions": 8, "lines": 16, "files": 2, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/blitz_info.py", "new_path": "weave/blitz_info.py", "filename": "blitz_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -36,7 +36,7 @@ class py_type >{public: enum { code = PyArray_CFLOAT};};\n class py_type >{public: enum { code = PyArray_CDOUBLE};};\n \n template\n-static blitz::Array convert_to_blitz(PyArrayObject* py_obj,const char* name)\n+static blitz::Array convert_to_blitz(PyArrayObject* arr_obj,const char* name)\n {\n \n //This is now handled externally (for now) to deal with exception/Abort issue\n@@ -59,7 +59,7 @@ class py_type >{public: enum { code = PyArray_CDOUBLE};};\n }\n \n template\n-static blitz::Array py_to_blitz(PyArrayObject* py_obj,const char* name)\n+static blitz::Array py_to_blitz(PyArrayObject* arr_obj,const char* name)\n {\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n", "added_lines": 2, "deleted_lines": 2, "source_code": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyArrayObject* arr_obj,const char* name)\n{\n\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n //conversion_numpy_check_size(arr_obj,N,name);\n //conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyArrayObject* arr_obj,const char* name)\n{\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n //numpy_check_size(arr_obj,N,name);\n //numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "source_code_before": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyArrayObject* py_obj,const char* name)\n{\n\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n //conversion_numpy_check_size(arr_obj,N,name);\n //conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyArrayObject* py_obj,const char* name)\n{\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n //numpy_check_size(arr_obj,N,name);\n //numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "methods": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 102, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "methods_before": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 102, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "changed_methods": [], "nloc": 98, "complexity": 2, "token_count": 120, "diff_parsed": { "added": [ "static blitz::Array convert_to_blitz(PyArrayObject* arr_obj,const char* name)", "static blitz::Array py_to_blitz(PyArrayObject* arr_obj,const char* name)" ], "deleted": [ "static blitz::Array convert_to_blitz(PyArrayObject* py_obj,const char* name)", "static blitz::Array py_to_blitz(PyArrayObject* py_obj,const char* name)" ] } }, { "old_path": "weave/blitz_spec.py", "new_path": "weave/blitz_spec.py", "filename": "blitz_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -42,10 +42,10 @@ def inline_decl_code(self):\n templ = '// blitz_array_declaration\\n' \\\n 'py_%(name)s= %(var_name)s;\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(py_%(name)s,\"%(name)s\");\\n' \\\n- 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);\\n' \\\n- 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)\\n' \\\n+ 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,\"%(name)s\");\\n' \\\n+ 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,\"%(name)s\");\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n- ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n+ ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n@@ -66,9 +66,9 @@ def standard_decl_code(self):\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n- 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");' \\\n- 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);' \\\n- 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)' \\\n+ 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");\\n' \\\n+ 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,\"%(name)s\");\\n' \\\n+ 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,\"%(name)s\");\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n", "added_lines": 6, "deleted_lines": 6, "source_code": "from base_spec import base_specification\nfrom scalar_spec import numeric_to_blitz_type_mapping\nfrom Numeric import *\nfrom types import *\nimport os\nimport blitz_info\n\nclass array_specification(base_specification):\n _build_information = [blitz_info.array_info()]\n\n def type_match(self,value):\n return type(value) is ArrayType\n\n def type_spec(self,name,value):\n # factory\n new_spec = array_specification()\n new_spec.name = name\n new_spec.numeric_type = value.typecode()\n new_spec.dims = len(value.shape)\n if new_spec.dims > 11:\n msg = \"Error converting variable '\" + name + \"'. \" \\\n \"blitz only supports arrays up to 11 dimensions.\"\n raise ValueError, msg\n return new_spec\n\n def declaration_code(self,templatize = 0,inline=0):\n if inline:\n code = self.inline_decl_code()\n else:\n code = self.standard_decl_code()\n return code\n\n def inline_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=1)\n arr_name = name + '_arr_obj'\n # We've had to inject quite a bit of code in here to handle the Aborted error\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'py_%(name)s= %(var_name)s;\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(py_%(name)s,\"%(name)s\");\\n' \\\n 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,\"%(name)s\");\\n' \\\n 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,\"%(name)s\");\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n # 'py_%(name)s= %(var_name)s;\\n' \\\n # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n # ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n\n def standard_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=0)\n arr_name = name + '_arr_obj'\n # We've had to inject quite a bit of code in here to handle the Aborted error\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");\\n' \\\n 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,\"%(name)s\");\\n' \\\n 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,\"%(name)s\");\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n # ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\\n # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n #def c_function_declaration_code(self):\n # \"\"\"\n # This doesn't pass the size through. That info is gonna have to\n # be redone in the c function.\n # \"\"\"\n # templ_dict = {}\n # templ_dict['type'] = numeric_to_blitz_type_mapping[self.numeric_type]\n # templ_dict['dims'] = self.dims\n # templ_dict['name'] = self.name\n # code = 'blitz::Array<%(type)s,%(dims)d> &%(name)s' % templ_dict\n # return code\n\n def local_dict_code(self):\n code = '// for now, array \"%s\" is not returned as arryas are edited' \\\n ' in place (should this change?)\\n' % (self.name)\n return code\n\n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\n def __repr__(self):\n msg = \"(array:: name: %s, type: %s, dims: %d)\" % \\\n (self.name, self.numeric_type, self.dims)\n return msg\n\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.dims, other.dims) or \\\n cmp(self.__class__, other.__class__)\n\n# stick this factory on the front of the type factories\nimport ext_tools\nblitz_aware_factories = [array_specification()] + ext_tools.default_type_factories\n", "source_code_before": "from base_spec import base_specification\nfrom scalar_spec import numeric_to_blitz_type_mapping\nfrom Numeric import *\nfrom types import *\nimport os\nimport blitz_info\n\nclass array_specification(base_specification):\n _build_information = [blitz_info.array_info()]\n\n def type_match(self,value):\n return type(value) is ArrayType\n\n def type_spec(self,name,value):\n # factory\n new_spec = array_specification()\n new_spec.name = name\n new_spec.numeric_type = value.typecode()\n new_spec.dims = len(value.shape)\n if new_spec.dims > 11:\n msg = \"Error converting variable '\" + name + \"'. \" \\\n \"blitz only supports arrays up to 11 dimensions.\"\n raise ValueError, msg\n return new_spec\n\n def declaration_code(self,templatize = 0,inline=0):\n if inline:\n code = self.inline_decl_code()\n else:\n code = self.standard_decl_code()\n return code\n\n def inline_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=1)\n arr_name = name + '_arr_obj'\n # We've had to inject quite a bit of code in here to handle the Aborted error\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'py_%(name)s= %(var_name)s;\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(py_%(name)s,\"%(name)s\");\\n' \\\n 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);\\n' \\\n 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)\\n' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n # 'py_%(name)s= %(var_name)s;\\n' \\\n # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n # ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\\n # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n\n def standard_decl_code(self):\n type = numeric_to_blitz_type_mapping[self.numeric_type]\n dims = self.dims\n name = self.name\n var_name = self.retrieve_py_variable(inline=0)\n arr_name = name + '_arr_obj'\n # We've had to inject quite a bit of code in here to handle the Aborted error\n # caused by exceptions. The templates made the easy fix (with MACROS) for all\n # other types difficult here. Oh well.\n templ = '// blitz_array_declaration\\n' \\\n 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");' \\\n 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);' \\\n 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)' \\\n 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\\n 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n # old version\n #templ = '// blitz_array_declaration\\n' \\\n # 'blitz::Array<%(type)s,%(dims)d> %(name)s =' \\\n # ' convert_to_blitz<%(type)s,%(dims)d>(%(var_name)s,\"%(name)s\");\\n' \\\n # 'blitz::TinyVector _N%(name)s = %(name)s.shape();\\n'\n code = templ % locals()\n return code\n #def c_function_declaration_code(self):\n # \"\"\"\n # This doesn't pass the size through. That info is gonna have to\n # be redone in the c function.\n # \"\"\"\n # templ_dict = {}\n # templ_dict['type'] = numeric_to_blitz_type_mapping[self.numeric_type]\n # templ_dict['dims'] = self.dims\n # templ_dict['name'] = self.name\n # code = 'blitz::Array<%(type)s,%(dims)d> &%(name)s' % templ_dict\n # return code\n\n def local_dict_code(self):\n code = '// for now, array \"%s\" is not returned as arryas are edited' \\\n ' in place (should this change?)\\n' % (self.name)\n return code\n\n def cleanup_code(self):\n # could use Py_DECREF here I think and save NULL test.\n code = \"Py_XDECREF(py_%s);\\n\" % self.name\n return code\n\n def __repr__(self):\n msg = \"(array:: name: %s, type: %s, dims: %d)\" % \\\n (self.name, self.numeric_type, self.dims)\n return msg\n\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.numeric_type,other.numeric_type) or \\\n cmp(self.dims, other.dims) or \\\n cmp(self.__class__, other.__class__)\n\n# stick this factory on the front of the type factories\nimport ext_tools\nblitz_aware_factories = [array_specification()] + ext_tools.default_type_factories\n", "methods": [ { "name": "type_match", "long_name": "type_match( self , value )", "filename": "blitz_spec.py", "nloc": 2, "complexity": 1, "token_count": 14, "parameters": [ "self", "value" ], "start_line": 11, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "blitz_spec.py", "nloc": 10, "complexity": 2, "token_count": 60, "parameters": [ "self", "name", "value" ], "start_line": 14, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "blitz_spec.py", "nloc": 6, "complexity": 2, "token_count": 34, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 31, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "inline_decl_code", "long_name": "inline_decl_code( self )", "filename": "blitz_spec.py", "nloc": 16, "complexity": 1, "token_count": 64, "parameters": [ "self" ], "start_line": 33, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "standard_decl_code", "long_name": "standard_decl_code( self )", "filename": "blitz_spec.py", "nloc": 15, "complexity": 1, "token_count": 62, "parameters": [ "self" ], "start_line": 59, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 94, "end_line": 97, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "blitz_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 99, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 104, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "blitz_spec.py", "nloc": 5, "complexity": 4, "token_count": 54, "parameters": [ "self", "other" ], "start_line": 109, "end_line": 114, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "methods_before": [ { "name": "type_match", "long_name": "type_match( self , value )", "filename": "blitz_spec.py", "nloc": 2, "complexity": 1, "token_count": 14, "parameters": [ "self", "value" ], "start_line": 11, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "blitz_spec.py", "nloc": 10, "complexity": 2, "token_count": 60, "parameters": [ "self", "name", "value" ], "start_line": 14, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "blitz_spec.py", "nloc": 6, "complexity": 2, "token_count": 34, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 31, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "inline_decl_code", "long_name": "inline_decl_code( self )", "filename": "blitz_spec.py", "nloc": 16, "complexity": 1, "token_count": 64, "parameters": [ "self" ], "start_line": 33, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "standard_decl_code", "long_name": "standard_decl_code( self )", "filename": "blitz_spec.py", "nloc": 15, "complexity": 1, "token_count": 62, "parameters": [ "self" ], "start_line": 59, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 94, "end_line": 97, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "cleanup_code", "long_name": "cleanup_code( self )", "filename": "blitz_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 99, "end_line": 102, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "blitz_spec.py", "nloc": 4, "complexity": 1, "token_count": 25, "parameters": [ "self" ], "start_line": 104, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "blitz_spec.py", "nloc": 5, "complexity": 4, "token_count": 54, "parameters": [ "self", "other" ], "start_line": 109, "end_line": 114, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "changed_methods": [ { "name": "inline_decl_code", "long_name": "inline_decl_code( self )", "filename": "blitz_spec.py", "nloc": 16, "complexity": 1, "token_count": 64, "parameters": [ "self" ], "start_line": 33, "end_line": 57, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 1 }, { "name": "standard_decl_code", "long_name": "standard_decl_code( self )", "filename": "blitz_spec.py", "nloc": 15, "complexity": 1, "token_count": 62, "parameters": [ "self" ], "start_line": 59, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 1 } ], "nloc": 75, "complexity": 14, "token_count": 402, "diff_parsed": { "added": [ " 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,\"%(name)s\");\\n' \\", " 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,\"%(name)s\");\\n' \\", " ' convert_to_blitz<%(type)s,%(dims)d>(%(arr_name)s,\"%(name)s\");\\n' \\", " 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");\\n' \\", " 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,\"%(name)s\");\\n' \\", " 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,\"%(name)s\");\\n' \\" ], "deleted": [ " 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);\\n' \\", " 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)\\n' \\", " ' convert_to_blitz<%(type)s,%(dims)d>(py_%(name)s,\"%(name)s\");\\n' \\", " 'PyArrayObject* %(arr_name)s = convert_to_numpy(%(var_name)s,\"%(name)s\");' \\", " 'conversion_numpy_check_size(%(arr_name)s,%(dims)s,%(name)s);' \\", " 'conversion_numpy_check_type(%(arr_name)s,py_type<%(type)s>::code,%(name)s)' \\" ] } } ] }, { "hash": "8d5d89db0f681e0ede61c5d0f7b71116cee69908", "msg": "fixing namespace issue for std::complex -- how did it ever wrok before?", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-20T03:39:14+00:00", "author_timezone": 0, "committer_date": "2002-01-20T03:39:14+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "a38603fb8206a6da4a6dd68d85958892ed5e3631" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 2, "insertions": 2, "lines": 4, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/blitz_info.py", "new_path": "weave/blitz_info.py", "filename": "blitz_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -32,8 +32,8 @@ class py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has trou\n class py_type{public: enum { code = PyArray_LONG};};\n class py_type{public: enum { code = PyArray_FLOAT};};\n class py_type{public: enum { code = PyArray_DOUBLE};};\n-class py_type >{public: enum { code = PyArray_CFLOAT};};\n-class py_type >{public: enum { code = PyArray_CDOUBLE};};\n+class py_type >{public: enum { code = PyArray_CFLOAT};};\n+class py_type >{public: enum { code = PyArray_CDOUBLE};};\n \n template\n static blitz::Array convert_to_blitz(PyArrayObject* arr_obj,const char* name)\n", "added_lines": 2, "deleted_lines": 2, "source_code": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyArrayObject* arr_obj,const char* name)\n{\n\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n //conversion_numpy_check_size(arr_obj,N,name);\n //conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyArrayObject* arr_obj,const char* name)\n{\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n //numpy_check_size(arr_obj,N,name);\n //numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "source_code_before": "\"\"\"\n build_info holds classes that define the information\n needed for building C++ extension modules for Python that\n handle different data types. The information includes\n such as include files, libraries, and even code snippets.\n \n array_info -- for building functions that use Python\n Numeric arrays.\n\"\"\"\n\nimport base_info\n\nblitz_support_code = \\\n\"\"\"\n\n// This should be declared only if they are used by some function\n// to keep from generating needless warnings. for now, we'll always\n// declare them.\n\nint _beg = blitz::fromStart;\nint _end = blitz::toEnd;\nblitz::Range _all = blitz::Range::all();\n\n// simple meta-program templates to specify python typecodes\n// for each of the numeric types.\ntemplate\nclass py_type{public: enum {code = 100};};\nclass py_type{public: enum {code = PyArray_CHAR};};\nclass py_type{public: enum { code = PyArray_UBYTE};};\nclass py_type{public: enum { code = PyArray_SHORT};};\nclass py_type{public: enum { code = PyArray_LONG};};// PyArray_INT has troubles;\nclass py_type{public: enum { code = PyArray_LONG};};\nclass py_type{public: enum { code = PyArray_FLOAT};};\nclass py_type{public: enum { code = PyArray_DOUBLE};};\nclass py_type >{public: enum { code = PyArray_CFLOAT};};\nclass py_type >{public: enum { code = PyArray_CDOUBLE};};\n\ntemplate\nstatic blitz::Array convert_to_blitz(PyArrayObject* arr_obj,const char* name)\n{\n\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = convert_to_numpy(py_obj,name);\n //conversion_numpy_check_size(arr_obj,N,name);\n //conversion_numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\ntemplate\nstatic blitz::Array py_to_blitz(PyArrayObject* arr_obj,const char* name)\n{\n //This is now handled externally (for now) to deal with exception/Abort issue\n //PyArrayObject* arr_obj = py_to_numpy(py_obj,name);\n //numpy_check_size(arr_obj,N,name);\n //numpy_check_type(arr_obj,py_type::code,name);\n \n blitz::TinyVector shape(0);\n blitz::TinyVector strides(0);\n int stride_acc = 1;\n //for (int i = N-1; i >=0; i--)\n for (int i = 0; i < N; i++)\n {\n shape[i] = arr_obj->dimensions[i];\n strides[i] = arr_obj->strides[i]/sizeof(T);\n }\n //return blitz::Array((T*) arr_obj->data,shape, \n return blitz::Array((T*) arr_obj->data,shape,strides,\n blitz::neverDeleteData);\n}\n\"\"\"\n\n\nimport standard_array_info\nimport os, blitz_info\nlocal_dir,junk = os.path.split(os.path.abspath(blitz_info.__file__)) \nblitz_dir = os.path.join(local_dir,'blitz-20001213')\n\nclass array_info(base_info.base_info):\n _include_dirs = [blitz_dir]\n _headers = ['\"blitz/array.h\"','\"Numeric/arrayobject.h\"','','']\n \n _support_code = [standard_array_info.array_convert_code,\n standard_array_info.type_check_code,\n standard_array_info.size_check_code,\n blitz_support_code]\n _module_init_code = [standard_array_info.numeric_init_code] \n \n # throw error if trying to use msvc compiler\n \n def check_compiler(self,compiler): \n msvc_msg = 'Unfortunately, the blitz arrays used to support numeric' \\\n ' arrays will not compile with MSVC.' \\\n ' Please try using mingw32 (www.mingw.org).'\n if compiler == 'msvc':\n return ValueError, self.msvc_msg ", "methods": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 102, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "methods_before": [ { "name": "check_compiler", "long_name": "check_compiler( self , compiler )", "filename": "blitz_info.py", "nloc": 6, "complexity": 2, "token_count": 25, "parameters": [ "self", "compiler" ], "start_line": 102, "end_line": 107, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 } ], "changed_methods": [], "nloc": 98, "complexity": 2, "token_count": 120, "diff_parsed": { "added": [ "class py_type >{public: enum { code = PyArray_CFLOAT};};", "class py_type >{public: enum { code = PyArray_CDOUBLE};};" ], "deleted": [ "class py_type >{public: enum { code = PyArray_CFLOAT};};", "class py_type >{public: enum { code = PyArray_CDOUBLE};};" ] } } ] }, { "hash": "7a770371db0fed625a9466c01694c6346601bcbd", "msg": "added assert_approx_equal to compare two numbers up to some significant digit. Contributed by Louis Luangkesorn", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-21T04:39:04+00:00", "author_timezone": 0, "committer_date": "2002-01-21T04:39:04+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "8d5d89db0f681e0ede61c5d0f7b71116cee69908" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 22, "lines": 23, "files": 1, "dmm_unit_size": 1.0, "dmm_unit_complexity": 1.0, "dmm_unit_interfacing": 0.0, "modified_files": [ { "old_path": "scipy_test/scipy_test.py", "new_path": "scipy_test/scipy_test.py", "filename": "scipy_test.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -233,8 +233,29 @@ def assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1):\n + '\\nACTUAL: ' + str(actual)\n assert round(abs(desired - actual),decimal) == 0, msg\n \n+def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1):\n+ \"\"\" Raise an assertion if two items are not\n+ equal. I think this should be part of unittest.py\n+ Approximately equal is defined as the number of significant digits \n+ correct\n+ \"\"\"\n+ msg = '\\nItems are not equal to %d significant digits:\\n' % significant\n+ msg += err_msg\n+ sc_desired = desired/pow(10,math.floor(math.log10(desired)))\n+ sc_actual = actual/pow(10,math.floor(math.log10(actual)))\n+ try:\n+ if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):\n+ msg = msg \\\n+ + 'DESIRED: ' + str(desired) \\\n+ + '\\nACTUAL: ' + str(actual)\n+ except:\n+ msg = msg \\\n+ + 'DESIRED: ' + str(desired) \\\n+ + '\\nACTUAL: ' + str(actual)\n+ assert math.fabs(sc_desired - sc_actual) < pow(10.,-1*significant), msg\n+ \n try:\n- # Numeric specific tests\n+ # Numeric specific testss\n from Numeric import *\n from fastumath import *\n \n", "added_lines": 22, "deleted_lines": 1, "source_code": "import os\n\ndef remove_ignored_patterns(files,pattern):\n from fnmatch import fnmatch\n good_files = []\n for file in files:\n if not fnmatch(file,pattern):\n good_files.append(file)\n return good_files \n \ndef remove_ignored_files(original,ignored_files,cur_dir):\n \"\"\" This is actually expanded to do pattern matching.\n \n \"\"\"\n if not ignored_files: ignored_files = []\n ignored_modules = map(lambda x: x+'.py',ignored_files)\n ignored_packages = ignored_files[:]\n # always ignore setup.py and __init__.py files\n ignored_files = ['setup.py','setup_*.py','__init__.py']\n ignored_files += ignored_modules + ignored_packages\n ignored_files = map(lambda x,cur_dir=cur_dir: os.path.join(cur_dir,x),\n ignored_files)\n #print 'ignored:', ignored_files \n #good_files = filter(lambda x,ignored = ignored_files: x not in ignored,\n # original)\n good_files = original\n for pattern in ignored_files:\n good_files = remove_ignored_patterns(good_files,pattern)\n \n return good_files\n \ndef harvest_modules(package,ignore=None):\n \"\"\"* Retreive a list of all modules that live within a package.\n\n Only retreive files that are immediate children of the\n package -- do not recurse through child packages or\n directories. The returned list contains actual modules, not\n just their names.\n *\"\"\"\n import os,sys\n\n d,f = os.path.split(package.__file__)\n\n # go through the directory and import every py file there.\n import glob\n common_dir = os.path.join(d,'*.py')\n py_files = glob.glob(common_dir)\n #py_files.remove(os.path.join(d,'__init__.py'))\n #py_files.remove(os.path.join(d,'setup.py'))\n \n py_files = remove_ignored_files(py_files,ignore,d)\n #print 'py_files:', py_files\n try:\n prefix = package.__name__\n except:\n prefix = ''\n \n all_modules = []\n for file in py_files:\n d,f = os.path.split(file)\n base,ext = os.path.splitext(f) \n mod = prefix + '.' + base\n #print 'module: import ' + mod\n try:\n exec ('import ' + mod)\n all_modules.append(eval(mod))\n except:\n print 'FAILURE to import ' + mod\n output_exception() \n \n return all_modules\n\ndef harvest_packages(package,ignore = None):\n \"\"\" Retreive a list of all sub-packages that live within a package.\n\n Only retreive packages that are immediate children of this\n package -- do not recurse through child packages or\n directories. The returned list contains actual package objects, not\n just their names.\n \"\"\"\n import os,sys\n join = os.path.join\n\n d,f = os.path.split(package.__file__)\n\n common_dir = os.path.abspath(d)\n all_files = os.listdir(d)\n \n all_files = remove_ignored_files(all_files,ignore,'')\n #print 'all_files:', all_files\n try:\n prefix = package.__name__\n except:\n prefix = ''\n all_packages = []\n for directory in all_files: \n path = join(common_dir,directory)\n if os.path.isdir(path) and \\\n os.path.exists(join(path,'__init__.py')):\n sub_package = prefix + '.' + directory\n #print 'sub-package import ' + sub_package\n try:\n exec ('import ' + sub_package)\n all_packages.append(eval(sub_package))\n except:\n print 'FAILURE to import ' + sub_package\n output_exception() \n return all_packages\n\ndef harvest_modules_and_packages(package,ignore=None):\n \"\"\" Retreive list of all packages and modules that live within a package.\n\n See harvest_packages() and harvest_modules()\n \"\"\"\n all = harvest_modules(package,ignore) + harvest_packages(package,ignore)\n return all\n\ndef harvest_test_suites(package,ignore = None):\n import unittest\n suites=[]\n test_modules = harvest_modules_and_packages(package,ignore)\n #for i in test_modules:\n # print i.__name__\n for module in test_modules:\n if hasattr(module,'test_suite'):\n try:\n suite = module.test_suite()\n if suite:\n suites.append(suite) \n else:\n msg = \" !! FAILURE without error - shouldn't happen\" + \\\n module.__name__ \n print msg\n except:\n print ' !! FAILURE building test for ', module.__name__ \n print ' ',\n output_exception() \n else:\n print 'No test suite found for ', module.__name__\n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef module_test(mod_name,mod_file):\n \"\"\"*\n\n *\"\"\"\n import os,sys,string\n #print 'testing', mod_name\n d,f = os.path.split(mod_file)\n\n # add the tests directory to the python path\n test_dir = os.path.join(d,'tests')\n sys.path.append(test_dir)\n\n # call the \"test_xxx.test()\" function for the appropriate\n # module.\n\n # This should deal with package naming issues correctly\n short_mod_name = string.split(mod_name,'.')[-1]\n test_module = 'test_' + short_mod_name\n test_string = 'import %s;reload(%s);%s.test()' % \\\n ((test_module,)*3)\n\n # This would be better cause it forces a reload of the orginal\n # module. It doesn't behave with packages however.\n #test_string = 'reload(%s);import %s;reload(%s);%s.test()' % \\\n # ((mod_name,) + (test_module,)*3)\n exec(test_string)\n\n # remove test directory from python path.\n sys.path = sys.path[:-1]\n\ndef module_test_suite(mod_name,mod_file):\n #try:\n import os,sys,string\n print ' creating test suite for:', mod_name\n d,f = os.path.split(mod_file)\n\n # add the tests directory to the python path\n test_dir = os.path.join(d,'tests')\n sys.path.append(test_dir)\n\n # call the \"test_xxx.test()\" function for the appropriate\n # module.\n\n # This should deal with package naming issues correctly\n short_mod_name = string.split(mod_name,'.')[-1]\n test_module = 'test_' + short_mod_name\n test_string = 'import %s;reload(%s);suite = %s.test_suite()' % ((test_module,)*3)\n #print test_string\n exec(test_string)\n\n # remove test directory from python path.\n sys.path = sys.path[:-1]\n return suite\n #except:\n # print ' !! FAILURE loading test suite from', test_module, ':'\n # print ' ',\n # output_exception() \n\n\n# Utility function to facilitate testing.\n\ndef assert_equal(actual,desired,err_msg='',verbose=1):\n \"\"\" Raise an assertion if two items are not\n equal. I think this should be part of unittest.py\n \"\"\"\n msg = '\\nItems are not equal:\\n' + err_msg\n try:\n if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n except:\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n assert desired == actual, msg\n\ndef assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1):\n \"\"\" Raise an assertion if two items are not\n equal. I think this should be part of unittest.py\n \"\"\"\n msg = '\\nItems are not equal:\\n' + err_msg\n try:\n if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n except:\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n assert round(abs(desired - actual),decimal) == 0, msg\n\ndef assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1):\n \"\"\" Raise an assertion if two items are not\n equal. I think this should be part of unittest.py\n Approximately equal is defined as the number of significant digits \n correct\n \"\"\"\n msg = '\\nItems are not equal to %d significant digits:\\n' % significant\n msg += err_msg\n sc_desired = desired/pow(10,math.floor(math.log10(desired)))\n sc_actual = actual/pow(10,math.floor(math.log10(actual)))\n try:\n if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n except:\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n assert math.fabs(sc_desired - sc_actual) < pow(10.,-1*significant), msg\n \ntry:\n # Numeric specific testss\n from Numeric import *\n from fastumath import *\n \n def assert_array_equal(x,y,err_msg=''):\n msg = '\\nArrays are not equal'\n try:\n assert alltrue(equal(shape(x),shape(y))),\\\n msg + ' (shapes mismatch):\\n\\t' + err_msg\n reduced = equal(x,y)\n assert alltrue(ravel(reduced)),\\\n msg + ':\\n\\t' + err_msg\n except ValueError:\n print shape(x),shape(y)\n raise ValueError, 'arrays are not equal'\n \n def assert_array_almost_equal(x,y,decimal=6,err_msg=''):\n msg = '\\nArrays are not almost equal'\n try:\n assert alltrue(equal(shape(x),shape(y))),\\\n msg + ' (shapes mismatch):\\n\\t' + err_msg\n reduced = equal(around(abs(x-y),decimal),0)\n assert alltrue(ravel(reduced)),\\\n msg + ':\\n\\t' + err_msg\n except ValueError:\n print sys.exc_value\n print shape(x),shape(y)\n print x, y\n raise ValueError, 'arrays are not almost equal'\nexcept:\n pass # Numeric not installed\n \nimport traceback,sys\ndef output_exception():\n try:\n type, value, tb = sys.exc_info()\n info = traceback.extract_tb(tb)\n #this is more verbose\n #traceback.print_exc()\n filename, lineno, function, text = info[-1] # last line only\n print \"%s:%d: %s: %s (in %s)\" %\\\n (filename, lineno, type.__name__, str(value), function)\n finally:\n type = value = tb = None # clean up\n", "source_code_before": "import os\n\ndef remove_ignored_patterns(files,pattern):\n from fnmatch import fnmatch\n good_files = []\n for file in files:\n if not fnmatch(file,pattern):\n good_files.append(file)\n return good_files \n \ndef remove_ignored_files(original,ignored_files,cur_dir):\n \"\"\" This is actually expanded to do pattern matching.\n \n \"\"\"\n if not ignored_files: ignored_files = []\n ignored_modules = map(lambda x: x+'.py',ignored_files)\n ignored_packages = ignored_files[:]\n # always ignore setup.py and __init__.py files\n ignored_files = ['setup.py','setup_*.py','__init__.py']\n ignored_files += ignored_modules + ignored_packages\n ignored_files = map(lambda x,cur_dir=cur_dir: os.path.join(cur_dir,x),\n ignored_files)\n #print 'ignored:', ignored_files \n #good_files = filter(lambda x,ignored = ignored_files: x not in ignored,\n # original)\n good_files = original\n for pattern in ignored_files:\n good_files = remove_ignored_patterns(good_files,pattern)\n \n return good_files\n \ndef harvest_modules(package,ignore=None):\n \"\"\"* Retreive a list of all modules that live within a package.\n\n Only retreive files that are immediate children of the\n package -- do not recurse through child packages or\n directories. The returned list contains actual modules, not\n just their names.\n *\"\"\"\n import os,sys\n\n d,f = os.path.split(package.__file__)\n\n # go through the directory and import every py file there.\n import glob\n common_dir = os.path.join(d,'*.py')\n py_files = glob.glob(common_dir)\n #py_files.remove(os.path.join(d,'__init__.py'))\n #py_files.remove(os.path.join(d,'setup.py'))\n \n py_files = remove_ignored_files(py_files,ignore,d)\n #print 'py_files:', py_files\n try:\n prefix = package.__name__\n except:\n prefix = ''\n \n all_modules = []\n for file in py_files:\n d,f = os.path.split(file)\n base,ext = os.path.splitext(f) \n mod = prefix + '.' + base\n #print 'module: import ' + mod\n try:\n exec ('import ' + mod)\n all_modules.append(eval(mod))\n except:\n print 'FAILURE to import ' + mod\n output_exception() \n \n return all_modules\n\ndef harvest_packages(package,ignore = None):\n \"\"\" Retreive a list of all sub-packages that live within a package.\n\n Only retreive packages that are immediate children of this\n package -- do not recurse through child packages or\n directories. The returned list contains actual package objects, not\n just their names.\n \"\"\"\n import os,sys\n join = os.path.join\n\n d,f = os.path.split(package.__file__)\n\n common_dir = os.path.abspath(d)\n all_files = os.listdir(d)\n \n all_files = remove_ignored_files(all_files,ignore,'')\n #print 'all_files:', all_files\n try:\n prefix = package.__name__\n except:\n prefix = ''\n all_packages = []\n for directory in all_files: \n path = join(common_dir,directory)\n if os.path.isdir(path) and \\\n os.path.exists(join(path,'__init__.py')):\n sub_package = prefix + '.' + directory\n #print 'sub-package import ' + sub_package\n try:\n exec ('import ' + sub_package)\n all_packages.append(eval(sub_package))\n except:\n print 'FAILURE to import ' + sub_package\n output_exception() \n return all_packages\n\ndef harvest_modules_and_packages(package,ignore=None):\n \"\"\" Retreive list of all packages and modules that live within a package.\n\n See harvest_packages() and harvest_modules()\n \"\"\"\n all = harvest_modules(package,ignore) + harvest_packages(package,ignore)\n return all\n\ndef harvest_test_suites(package,ignore = None):\n import unittest\n suites=[]\n test_modules = harvest_modules_and_packages(package,ignore)\n #for i in test_modules:\n # print i.__name__\n for module in test_modules:\n if hasattr(module,'test_suite'):\n try:\n suite = module.test_suite()\n if suite:\n suites.append(suite) \n else:\n msg = \" !! FAILURE without error - shouldn't happen\" + \\\n module.__name__ \n print msg\n except:\n print ' !! FAILURE building test for ', module.__name__ \n print ' ',\n output_exception() \n else:\n print 'No test suite found for ', module.__name__\n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef module_test(mod_name,mod_file):\n \"\"\"*\n\n *\"\"\"\n import os,sys,string\n #print 'testing', mod_name\n d,f = os.path.split(mod_file)\n\n # add the tests directory to the python path\n test_dir = os.path.join(d,'tests')\n sys.path.append(test_dir)\n\n # call the \"test_xxx.test()\" function for the appropriate\n # module.\n\n # This should deal with package naming issues correctly\n short_mod_name = string.split(mod_name,'.')[-1]\n test_module = 'test_' + short_mod_name\n test_string = 'import %s;reload(%s);%s.test()' % \\\n ((test_module,)*3)\n\n # This would be better cause it forces a reload of the orginal\n # module. It doesn't behave with packages however.\n #test_string = 'reload(%s);import %s;reload(%s);%s.test()' % \\\n # ((mod_name,) + (test_module,)*3)\n exec(test_string)\n\n # remove test directory from python path.\n sys.path = sys.path[:-1]\n\ndef module_test_suite(mod_name,mod_file):\n #try:\n import os,sys,string\n print ' creating test suite for:', mod_name\n d,f = os.path.split(mod_file)\n\n # add the tests directory to the python path\n test_dir = os.path.join(d,'tests')\n sys.path.append(test_dir)\n\n # call the \"test_xxx.test()\" function for the appropriate\n # module.\n\n # This should deal with package naming issues correctly\n short_mod_name = string.split(mod_name,'.')[-1]\n test_module = 'test_' + short_mod_name\n test_string = 'import %s;reload(%s);suite = %s.test_suite()' % ((test_module,)*3)\n #print test_string\n exec(test_string)\n\n # remove test directory from python path.\n sys.path = sys.path[:-1]\n return suite\n #except:\n # print ' !! FAILURE loading test suite from', test_module, ':'\n # print ' ',\n # output_exception() \n\n\n# Utility function to facilitate testing.\n\ndef assert_equal(actual,desired,err_msg='',verbose=1):\n \"\"\" Raise an assertion if two items are not\n equal. I think this should be part of unittest.py\n \"\"\"\n msg = '\\nItems are not equal:\\n' + err_msg\n try:\n if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n except:\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n assert desired == actual, msg\n\ndef assert_almost_equal(actual,desired,decimal=7,err_msg='',verbose=1):\n \"\"\" Raise an assertion if two items are not\n equal. I think this should be part of unittest.py\n \"\"\"\n msg = '\\nItems are not equal:\\n' + err_msg\n try:\n if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n except:\n msg = msg \\\n + 'DESIRED: ' + str(desired) \\\n + '\\nACTUAL: ' + str(actual)\n assert round(abs(desired - actual),decimal) == 0, msg\n\ntry:\n # Numeric specific tests\n from Numeric import *\n from fastumath import *\n \n def assert_array_equal(x,y,err_msg=''):\n msg = '\\nArrays are not equal'\n try:\n assert alltrue(equal(shape(x),shape(y))),\\\n msg + ' (shapes mismatch):\\n\\t' + err_msg\n reduced = equal(x,y)\n assert alltrue(ravel(reduced)),\\\n msg + ':\\n\\t' + err_msg\n except ValueError:\n print shape(x),shape(y)\n raise ValueError, 'arrays are not equal'\n \n def assert_array_almost_equal(x,y,decimal=6,err_msg=''):\n msg = '\\nArrays are not almost equal'\n try:\n assert alltrue(equal(shape(x),shape(y))),\\\n msg + ' (shapes mismatch):\\n\\t' + err_msg\n reduced = equal(around(abs(x-y),decimal),0)\n assert alltrue(ravel(reduced)),\\\n msg + ':\\n\\t' + err_msg\n except ValueError:\n print sys.exc_value\n print shape(x),shape(y)\n print x, y\n raise ValueError, 'arrays are not almost equal'\nexcept:\n pass # Numeric not installed\n \nimport traceback,sys\ndef output_exception():\n try:\n type, value, tb = sys.exc_info()\n info = traceback.extract_tb(tb)\n #this is more verbose\n #traceback.print_exc()\n filename, lineno, function, text = info[-1] # last line only\n print \"%s:%d: %s: %s (in %s)\" %\\\n (filename, lineno, type.__name__, str(value), function)\n finally:\n type = value = tb = None # clean up\n", "methods": [ { "name": "remove_ignored_patterns", "long_name": "remove_ignored_patterns( files , pattern )", "filename": "scipy_test.py", "nloc": 7, "complexity": 3, "token_count": 37, "parameters": [ "files", "pattern" ], "start_line": 3, "end_line": 9, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "remove_ignored_files", "long_name": "remove_ignored_files( original , ignored_files , cur_dir )", "filename": "scipy_test.py", "nloc": 12, "complexity": 3, "token_count": 93, "parameters": [ "original", "ignored_files", "cur_dir" ], "start_line": 11, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 0 }, { "name": "harvest_modules", "long_name": "harvest_modules( package , ignore = None )", "filename": "scipy_test.py", "nloc": 23, "complexity": 4, "token_count": 140, "parameters": [ "package", "ignore" ], "start_line": 32, "end_line": 71, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 40, "top_nesting_level": 0 }, { "name": "harvest_packages", "long_name": "harvest_packages( package , ignore = None )", "filename": "scipy_test.py", "nloc": 24, "complexity": 6, "token_count": 152, "parameters": [ "package", "ignore" ], "start_line": 73, "end_line": 108, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "harvest_modules_and_packages", "long_name": "harvest_modules_and_packages( package , ignore = None )", "filename": "scipy_test.py", "nloc": 3, "complexity": 1, "token_count": 27, "parameters": [ "package", "ignore" ], "start_line": 110, "end_line": 116, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "harvest_test_suites", "long_name": "harvest_test_suites( package , ignore = None )", "filename": "scipy_test.py", "nloc": 22, "complexity": 5, "token_count": 98, "parameters": [ "package", "ignore" ], "start_line": 118, "end_line": 141, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 24, "top_nesting_level": 0 }, { "name": "module_test", "long_name": "module_test( mod_name , mod_file )", "filename": "scipy_test.py", "nloc": 11, "complexity": 1, "token_count": 94, "parameters": [ "mod_name", "mod_file" ], "start_line": 143, "end_line": 171, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 29, "top_nesting_level": 0 }, { "name": "module_test_suite", "long_name": "module_test_suite( mod_name , mod_file )", "filename": "scipy_test.py", "nloc": 12, "complexity": 1, "token_count": 98, "parameters": [ "mod_name", "mod_file" ], "start_line": 173, "end_line": 195, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 0 }, { "name": "assert_equal", "long_name": "assert_equal( actual , desired , err_msg = '' , verbose = 1 )", "filename": "scipy_test.py", "nloc": 12, "complexity": 5, "token_count": 92, "parameters": [ "actual", "desired", "err_msg", "verbose" ], "start_line": 204, "end_line": 218, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "assert_almost_equal", "long_name": "assert_almost_equal( actual , desired , decimal = 7 , err_msg = '' , verbose = 1 )", "filename": "scipy_test.py", "nloc": 12, "complexity": 5, "token_count": 106, "parameters": [ "actual", "desired", "decimal", "err_msg", "verbose" ], "start_line": 220, "end_line": 234, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "assert_approx_equal", "long_name": "assert_approx_equal( actual , desired , significant = 7 , err_msg = '' , verbose = 1 )", "filename": "scipy_test.py", "nloc": 15, "complexity": 5, "token_count": 155, "parameters": [ "actual", "desired", "significant", "err_msg", "verbose" ], "start_line": 236, "end_line": 255, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 0 }, { "name": "assert_array_equal", "long_name": "assert_array_equal( x , y , err_msg = '' )", "filename": "scipy_test.py", "nloc": 11, "complexity": 2, "token_count": 79, "parameters": [ "x", "y", "err_msg" ], "start_line": 262, "end_line": 272, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "assert_array_almost_equal", "long_name": "assert_array_almost_equal( x , y , decimal = 6 , err_msg = '' )", "filename": "scipy_test.py", "nloc": 13, "complexity": 2, "token_count": 101, "parameters": [ "x", "y", "decimal", "err_msg" ], "start_line": 274, "end_line": 286, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "output_exception", "long_name": "output_exception( )", "filename": "scipy_test.py", "nloc": 9, "complexity": 2, "token_count": 67, "parameters": [], "start_line": 291, "end_line": 301, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 } ], "methods_before": [ { "name": "remove_ignored_patterns", "long_name": "remove_ignored_patterns( files , pattern )", "filename": "scipy_test.py", "nloc": 7, "complexity": 3, "token_count": 37, "parameters": [ "files", "pattern" ], "start_line": 3, "end_line": 9, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "remove_ignored_files", "long_name": "remove_ignored_files( original , ignored_files , cur_dir )", "filename": "scipy_test.py", "nloc": 12, "complexity": 3, "token_count": 93, "parameters": [ "original", "ignored_files", "cur_dir" ], "start_line": 11, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 0 }, { "name": "harvest_modules", "long_name": "harvest_modules( package , ignore = None )", "filename": "scipy_test.py", "nloc": 23, "complexity": 4, "token_count": 140, "parameters": [ "package", "ignore" ], "start_line": 32, "end_line": 71, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 40, "top_nesting_level": 0 }, { "name": "harvest_packages", "long_name": "harvest_packages( package , ignore = None )", "filename": "scipy_test.py", "nloc": 24, "complexity": 6, "token_count": 152, "parameters": [ "package", "ignore" ], "start_line": 73, "end_line": 108, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "harvest_modules_and_packages", "long_name": "harvest_modules_and_packages( package , ignore = None )", "filename": "scipy_test.py", "nloc": 3, "complexity": 1, "token_count": 27, "parameters": [ "package", "ignore" ], "start_line": 110, "end_line": 116, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 7, "top_nesting_level": 0 }, { "name": "harvest_test_suites", "long_name": "harvest_test_suites( package , ignore = None )", "filename": "scipy_test.py", "nloc": 22, "complexity": 5, "token_count": 98, "parameters": [ "package", "ignore" ], "start_line": 118, "end_line": 141, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 24, "top_nesting_level": 0 }, { "name": "module_test", "long_name": "module_test( mod_name , mod_file )", "filename": "scipy_test.py", "nloc": 11, "complexity": 1, "token_count": 94, "parameters": [ "mod_name", "mod_file" ], "start_line": 143, "end_line": 171, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 29, "top_nesting_level": 0 }, { "name": "module_test_suite", "long_name": "module_test_suite( mod_name , mod_file )", "filename": "scipy_test.py", "nloc": 12, "complexity": 1, "token_count": 98, "parameters": [ "mod_name", "mod_file" ], "start_line": 173, "end_line": 195, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 23, "top_nesting_level": 0 }, { "name": "assert_equal", "long_name": "assert_equal( actual , desired , err_msg = '' , verbose = 1 )", "filename": "scipy_test.py", "nloc": 12, "complexity": 5, "token_count": 92, "parameters": [ "actual", "desired", "err_msg", "verbose" ], "start_line": 204, "end_line": 218, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "assert_almost_equal", "long_name": "assert_almost_equal( actual , desired , decimal = 7 , err_msg = '' , verbose = 1 )", "filename": "scipy_test.py", "nloc": 12, "complexity": 5, "token_count": 106, "parameters": [ "actual", "desired", "decimal", "err_msg", "verbose" ], "start_line": 220, "end_line": 234, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "assert_array_equal", "long_name": "assert_array_equal( x , y , err_msg = '' )", "filename": "scipy_test.py", "nloc": 11, "complexity": 2, "token_count": 79, "parameters": [ "x", "y", "err_msg" ], "start_line": 241, "end_line": 251, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 1 }, { "name": "assert_array_almost_equal", "long_name": "assert_array_almost_equal( x , y , decimal = 6 , err_msg = '' )", "filename": "scipy_test.py", "nloc": 13, "complexity": 2, "token_count": 101, "parameters": [ "x", "y", "decimal", "err_msg" ], "start_line": 253, "end_line": 265, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 13, "top_nesting_level": 1 }, { "name": "output_exception", "long_name": "output_exception( )", "filename": "scipy_test.py", "nloc": 9, "complexity": 2, "token_count": 67, "parameters": [], "start_line": 270, "end_line": 280, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 11, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "assert_approx_equal", "long_name": "assert_approx_equal( actual , desired , significant = 7 , err_msg = '' , verbose = 1 )", "filename": "scipy_test.py", "nloc": 15, "complexity": 5, "token_count": 155, "parameters": [ "actual", "desired", "significant", "err_msg", "verbose" ], "start_line": 236, "end_line": 255, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 20, "top_nesting_level": 0 } ], "nloc": 193, "complexity": 45, "token_count": 1372, "diff_parsed": { "added": [ "def assert_approx_equal(actual,desired,significant=7,err_msg='',verbose=1):", " \"\"\" Raise an assertion if two items are not", " equal. I think this should be part of unittest.py", " Approximately equal is defined as the number of significant digits", " correct", " \"\"\"", " msg = '\\nItems are not equal to %d significant digits:\\n' % significant", " msg += err_msg", " sc_desired = desired/pow(10,math.floor(math.log10(desired)))", " sc_actual = actual/pow(10,math.floor(math.log10(actual)))", " try:", " if ( verbose and len(str(desired)) < 100 and len(str(actual)) ):", " msg = msg \\", " + 'DESIRED: ' + str(desired) \\", " + '\\nACTUAL: ' + str(actual)", " except:", " msg = msg \\", " + 'DESIRED: ' + str(desired) \\", " + '\\nACTUAL: ' + str(actual)", " assert math.fabs(sc_desired - sc_actual) < pow(10.,-1*significant), msg", "", " # Numeric specific testss" ], "deleted": [ " # Numeric specific tests" ] } } ] }, { "hash": "ed00c6fa2ce5fe3bafb58ae5a917180cfd1102fe", "msg": "added macros for convert_to_list, etc. Somehow, these had been left out in the previous changes.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-22T19:14:04+00:00", "author_timezone": 0, "committer_date": "2002-01-22T19:14:04+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "7a770371db0fed625a9466c01694c6346601bcbd" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 6, "insertions": 8, "lines": 14, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/cxx_info.py", "new_path": "weave/cxx_info.py", "filename": "cxx_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -37,16 +37,18 @@ class list_handler\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n+ Py::List py_to_list(PyObject* py_obj,const char* name)\n+ {\n+ if (!py_obj || !PyList_Check(py_obj))\n+ handle_bad_type(py_obj,\"list\", name);\n+ return Py::List(py_obj);\n+ }\n };\n \n list_handler x__list_handler = list_handler();\n+#define convert_to_list(py_obj,name) x__list_handler.convert_to_list(py_obj,name)\n+#define py_to_list(py_obj,name) x__list_handler.py_to_list(py_obj,name)\n \n-static Py::List py_to_list(PyObject* py_obj,const char* name)\n-{\n- if (!py_obj || !PyList_Check(py_obj))\n- handle_bad_type(py_obj,\"list\", name);\n- return Py::List(py_obj);\n-}\n \"\"\"\n \n dict_support_code = \\\n", "added_lines": 8, "deleted_lines": 6, "source_code": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\npublic:\n static Py::String convert_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n Py::String py_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\n\nstring_handler x__string_handler = string_handler();\n\n#define convert_to_string(py_obj,name) x__string_handler.convert_to_string(py_obj,name)\n#define py_to_string(py_obj,name) x__string_handler.py_to_string(py_obj,name)\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\npublic:\n Py::List convert_to_list(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n Py::List py_to_list(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nlist_handler x__list_handler = list_handler();\n#define convert_to_list(py_obj,name) x__list_handler.convert_to_list(py_obj,name)\n#define py_to_list(py_obj,name) x__list_handler.py_to_list(py_obj,name)\n\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\npublic:\n Py::Dict convert_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n Py::Dict py_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n};\n\ndict_handler x__dict_handler = dict_handler();\n#define convert_to_dict(py_obj,name) x__dict_handler.convert_to_dict(py_obj,name)\n#define py_to_dict(py_obj,name) x__dict_handler.py_to_dict(py_obj,name)\n\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\npublic:\n Py::Tuple convert_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n Py::Tuple py_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\ntuple_handler x__tuple_handler = tuple_handler();\n#define convert_to_tuple(py_obj,name) x__tuple_handler.convert_to_tuple(py_obj,name)\n#define py_to_tuple(py_obj,name) x__tuple_handler.py_to_tuple(py_obj,name)\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "source_code_before": "import base_info, common_info\n\nstring_support_code = \\\n\"\"\"\nclass string_handler\n{\npublic:\n static Py::String convert_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_conversion_error(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n Py::String py_to_string(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyString_Check(py_obj))\n handle_bad_type(py_obj,\"string\", name);\n return Py::String(py_obj);\n }\n};\n\nstring_handler x__string_handler = string_handler();\n\n#define convert_to_string(py_obj,name) x__string_handler.convert_to_string(py_obj,name)\n#define py_to_string(py_obj,name) x__string_handler.py_to_string(py_obj,name)\n\"\"\"\n\nlist_support_code = \\\n\"\"\"\n\nclass list_handler\n{\npublic:\n Py::List convert_to_list(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyList_Check(py_obj))\n handle_conversion_error(py_obj,\"list\", name);\n return Py::List(py_obj);\n }\n};\n\nlist_handler x__list_handler = list_handler();\n\nstatic Py::List py_to_list(PyObject* py_obj,const char* name)\n{\n if (!py_obj || !PyList_Check(py_obj))\n handle_bad_type(py_obj,\"list\", name);\n return Py::List(py_obj);\n}\n\"\"\"\n\ndict_support_code = \\\n\"\"\"\nclass dict_handler\n{\npublic:\n Py::Dict convert_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_conversion_error(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n Py::Dict py_to_dict(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj,\"dict\", name);\n return Py::Dict(py_obj);\n }\n};\n\ndict_handler x__dict_handler = dict_handler();\n#define convert_to_dict(py_obj,name) x__dict_handler.convert_to_dict(py_obj,name)\n#define py_to_dict(py_obj,name) x__dict_handler.py_to_dict(py_obj,name)\n\n\"\"\"\n\ntuple_support_code = \\\n\"\"\"\nclass tuple_handler\n{\npublic:\n Py::Tuple convert_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_conversion_error(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n Py::Tuple py_to_tuple(PyObject* py_obj,const char* name)\n {\n if (!py_obj || !PyTuple_Check(py_obj))\n handle_bad_type(py_obj,\"tuple\", name);\n return Py::Tuple(py_obj);\n }\n};\n\ntuple_handler x__tuple_handler = tuple_handler();\n#define convert_to_tuple(py_obj,name) x__tuple_handler.convert_to_tuple(py_obj,name)\n#define py_to_tuple(py_obj,name) x__tuple_handler.py_to_tuple(py_obj,name)\n\"\"\"\n\nimport os, cxx_info\nlocal_dir,junk = os.path.split(os.path.abspath(cxx_info.__file__)) \ncxx_dir = os.path.join(local_dir,'CXX')\n\nclass cxx_info(base_info.base_info):\n _headers = ['\"CXX/Objects.hxx\"','\"CXX/Extensions.hxx\"','']\n _include_dirs = [local_dir]\n\n # should these be built to a library??\n _sources = [os.path.join(cxx_dir,'cxxsupport.cxx'),\n os.path.join(cxx_dir,'cxx_extensions.cxx'),\n os.path.join(cxx_dir,'IndirectPythonInterface.cxx'),\n os.path.join(cxx_dir,'cxxextensions.c')]\n _support_code = [string_support_code,list_support_code, dict_support_code,\n tuple_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 109, "complexity": 0, "token_count": 137, "diff_parsed": { "added": [ " Py::List py_to_list(PyObject* py_obj,const char* name)", " {", " if (!py_obj || !PyList_Check(py_obj))", " handle_bad_type(py_obj,\"list\", name);", " return Py::List(py_obj);", " }", "#define convert_to_list(py_obj,name) x__list_handler.convert_to_list(py_obj,name)", "#define py_to_list(py_obj,name) x__list_handler.py_to_list(py_obj,name)" ], "deleted": [ "static Py::List py_to_list(PyObject* py_obj,const char* name)", "{", " if (!py_obj || !PyList_Check(py_obj))", " handle_bad_type(py_obj,\"list\", name);", " return Py::List(py_obj);", "}" ] } } ] }, { "hash": "e03b4d87272bdd651612d91bd68b4d1d78b5a97e", "msg": "added a few tests to catch problems in sequence conversions", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-22T20:37:01+00:00", "author_timezone": 0, "committer_date": "2002-01-22T20:37:01+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "ed00c6fa2ce5fe3bafb58ae5a917180cfd1102fe" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 0, "insertions": 36, "lines": 36, "files": 1, "dmm_unit_size": 1.0, "dmm_unit_complexity": 1.0, "dmm_unit_interfacing": 1.0, "modified_files": [ { "old_path": null, "new_path": "weave/tests/test_sequence_spec.py", "filename": "test_sequence_spec.py", "extension": "py", "change_type": "ADD", "diff": "@@ -0,0 +1,36 @@\n+import unittest\n+\n+from scipy_distutils.misc_util import add_grandparent_to_path, restore_path\n+\n+add_grandparent_to_path(__name__)\n+import inline_tools\n+restore_path()\n+ \n+class test_sequence_specification(unittest.TestCase): \n+ def check_convert_to_dict(self):\n+ d = {}\n+ inline_tools.inline(\"\",['d']) \n+ def check_convert_to_list(self): \n+ l = []\n+ inline_tools.inline(\"\",['l']) \n+ def check_convert_to_string(self): \n+ s = 'hello'\n+ inline_tools.inline(\"\",['s']) \n+ def check_convert_to_tuple(self): \n+ t = ()\n+ inline_tools.inline(\"\",['t']) \n+ \n+def test_suite():\n+ suites = [] \n+ suites.append( unittest.makeSuite(test_sequence_specification,'check_'))\n+ total_suite = unittest.TestSuite(suites)\n+ return total_suite\n+\n+def test():\n+ all_tests = test_suite()\n+ runner = unittest.TextTestRunner()\n+ runner.run(all_tests)\n+ return runner\n+\n+if __name__ == \"__main__\":\n+ test()\n", "added_lines": 36, "deleted_lines": 0, "source_code": "import unittest\n\nfrom scipy_distutils.misc_util import add_grandparent_to_path, restore_path\n\nadd_grandparent_to_path(__name__)\nimport inline_tools\nrestore_path()\n \nclass test_sequence_specification(unittest.TestCase): \n def check_convert_to_dict(self):\n d = {}\n inline_tools.inline(\"\",['d']) \n def check_convert_to_list(self): \n l = []\n inline_tools.inline(\"\",['l']) \n def check_convert_to_string(self): \n s = 'hello'\n inline_tools.inline(\"\",['s']) \n def check_convert_to_tuple(self): \n t = ()\n inline_tools.inline(\"\",['t']) \n \ndef test_suite():\n suites = [] \n suites.append( unittest.makeSuite(test_sequence_specification,'check_'))\n total_suite = unittest.TestSuite(suites)\n return total_suite\n\ndef test():\n all_tests = test_suite()\n runner = unittest.TextTestRunner()\n runner.run(all_tests)\n return runner\n\nif __name__ == \"__main__\":\n test()\n", "source_code_before": null, "methods": [ { "name": "check_convert_to_dict", "long_name": "check_convert_to_dict( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 10, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_convert_to_list", "long_name": "check_convert_to_list( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_convert_to_string", "long_name": "check_convert_to_string( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 16, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_convert_to_tuple", "long_name": "check_convert_to_tuple( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 19, "end_line": 21, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [], "start_line": 23, "end_line": 27, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "test_sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 29, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "methods_before": [], "changed_methods": [ { "name": "check_convert_to_list", "long_name": "check_convert_to_list( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "test_sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 24, "parameters": [], "start_line": 29, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 }, { "name": "check_convert_to_dict", "long_name": "check_convert_to_dict( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 10, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_convert_to_string", "long_name": "check_convert_to_string( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 18, "parameters": [ "self" ], "start_line": 16, "end_line": 18, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "check_convert_to_tuple", "long_name": "check_convert_to_tuple( self )", "filename": "test_sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 19, "parameters": [ "self" ], "start_line": 19, "end_line": 21, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "test_sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 31, "parameters": [], "start_line": 23, "end_line": 27, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 0 } ], "nloc": 30, "complexity": 6, "token_count": 171, "diff_parsed": { "added": [ "import unittest", "", "from scipy_distutils.misc_util import add_grandparent_to_path, restore_path", "", "add_grandparent_to_path(__name__)", "import inline_tools", "restore_path()", "", "class test_sequence_specification(unittest.TestCase):", " def check_convert_to_dict(self):", " d = {}", " inline_tools.inline(\"\",['d'])", " def check_convert_to_list(self):", " l = []", " inline_tools.inline(\"\",['l'])", " def check_convert_to_string(self):", " s = 'hello'", " inline_tools.inline(\"\",['s'])", " def check_convert_to_tuple(self):", " t = ()", " inline_tools.inline(\"\",['t'])", "", "def test_suite():", " suites = []", " suites.append( unittest.makeSuite(test_sequence_specification,'check_'))", " total_suite = unittest.TestSuite(suites)", " return total_suite", "", "def test():", " all_tests = test_suite()", " runner = unittest.TextTestRunner()", " runner.run(all_tests)", " return runner", "", "if __name__ == \"__main__\":", " test()" ], "deleted": [] } } ] }, { "hash": "227c397f7f597f58dc068e98021d4805b667e642", "msg": "several issues with tuple,dict,and list conversions were solved. Also, NameError is now caught and checked for ConversionError in inline_tools. This can be an issue when something like inline(\"\",['a']) is called and then inline(\"\",['b']) is called. It hadn't occured to me that the names had to be the same from call to call, but I guess they do or we get a recompile.", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-22T20:43:22+00:00", "author_timezone": 0, "committer_date": "2002-01-22T20:43:22+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "e03b4d87272bdd651612d91bd68b4d1d78b5a97e" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 5, "insertions": 24, "lines": 29, "files": 3, "dmm_unit_size": 0.3333333333333333, "dmm_unit_complexity": 0.3333333333333333, "dmm_unit_interfacing": 0.3333333333333333, "modified_files": [ { "old_path": "weave/inline_info.py", "new_path": "weave/inline_info.py", "filename": "inline_info.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -3,7 +3,7 @@\n void handle_variable_not_found(char* var_name)\n {\n char msg[500];\n- sprintf(msg,\"variable '%s' not found in local or global scope.\",var_name);\n+ sprintf(msg,\"Conversion Error: variable '%s' not found in local or global scope.\",var_name);\n throw_error(PyExc_NameError,msg);\n }\n PyObject* get_variable(char* name,PyObject* locals, PyObject* globals)\n", "added_lines": 1, "deleted_lines": 1, "source_code": "get_variable_support_code = \\\n\"\"\"\nvoid handle_variable_not_found(char* var_name)\n{\n char msg[500];\n sprintf(msg,\"Conversion Error: variable '%s' not found in local or global scope.\",var_name);\n throw_error(PyExc_NameError,msg);\n}\nPyObject* get_variable(char* name,PyObject* locals, PyObject* globals)\n{\n // no checking done for error -- locals and globals should\n // already be validated as dictionaries. If var is NULL, the\n // function calling this should handle it.\n PyObject* var = NULL;\n var = PyDict_GetItemString(locals,name);\n if (!var)\n {\n var = PyDict_GetItemString(globals,name);\n }\n if (!var)\n handle_variable_not_found(name);\n return var;\n}\n\"\"\"\n\npy_to_raw_dict_support_code = \\\n\"\"\"\nPyObject* py_to_raw_dict(PyObject* py_obj, char* name)\n{\n // simply check that the value is a valid dictionary pointer.\n if(!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj, \"dictionary\", name);\n return py_obj;\n}\n\"\"\"\n\nimport base_info\nclass inline_info(base_info.base_info):\n _support_code = [get_variable_support_code, py_to_raw_dict_support_code]\n", "source_code_before": "get_variable_support_code = \\\n\"\"\"\nvoid handle_variable_not_found(char* var_name)\n{\n char msg[500];\n sprintf(msg,\"variable '%s' not found in local or global scope.\",var_name);\n throw_error(PyExc_NameError,msg);\n}\nPyObject* get_variable(char* name,PyObject* locals, PyObject* globals)\n{\n // no checking done for error -- locals and globals should\n // already be validated as dictionaries. If var is NULL, the\n // function calling this should handle it.\n PyObject* var = NULL;\n var = PyDict_GetItemString(locals,name);\n if (!var)\n {\n var = PyDict_GetItemString(globals,name);\n }\n if (!var)\n handle_variable_not_found(name);\n return var;\n}\n\"\"\"\n\npy_to_raw_dict_support_code = \\\n\"\"\"\nPyObject* py_to_raw_dict(PyObject* py_obj, char* name)\n{\n // simply check that the value is a valid dictionary pointer.\n if(!py_obj || !PyDict_Check(py_obj))\n handle_bad_type(py_obj, \"dictionary\", name);\n return py_obj;\n}\n\"\"\"\n\nimport base_info\nclass inline_info(base_info.base_info):\n _support_code = [get_variable_support_code, py_to_raw_dict_support_code]\n", "methods": [], "methods_before": [], "changed_methods": [], "nloc": 37, "complexity": 0, "token_count": 25, "diff_parsed": { "added": [ " sprintf(msg,\"Conversion Error: variable '%s' not found in local or global scope.\",var_name);" ], "deleted": [ " sprintf(msg,\"variable '%s' not found in local or global scope.\",var_name);" ] } }, { "old_path": "weave/inline_tools.py", "new_path": "weave/inline_tools.py", "filename": "inline_tools.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -296,12 +296,18 @@ def inline(code,arg_names=[],local_dict = None, global_dict = None,\n try:\n results = apply(function_cache[code],(local_dict,global_dict))\n return results\n- except TypeError, msg: # should specify argument types here.\n- msg = str(msg)\n+ except TypeError, msg: \n+ msg = str(msg).strip()\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n+ except NameError, msg: \n+ msg = str(msg).strip()\n+ if msg[:16] == \"Conversion Error\":\n+ pass\n+ else:\n+ raise NameError, msg\n except KeyError:\n pass\n # 2. try function catalog\n@@ -347,7 +353,12 @@ def attempt_function_call(code,local_dict,global_dict):\n pass\n else:\n raise TypeError, msg\n- \n+ except NameError, msg: \n+ msg = str(msg).strip()\n+ if msg[:16] == \"Conversion Error\":\n+ pass\n+ else:\n+ raise NameError, msg \n # 3. try persistent catalog\n module_dir = global_dict.get('__file__',None)\n function_list = function_catalog.get_functions(code,module_dir)\n", "added_lines": 14, "deleted_lines": 3, "source_code": "# should re-write compiled functions to take a local and global dict\n# as input.\nimport sys,os\nimport ext_tools\nimport string\nimport catalog\nimport inline_info, cxx_info\n\n# not an easy way for the user_path_list to come in here.\n# the PYTHONCOMPILED environment variable offers the most hope.\n\nfunction_catalog = catalog.catalog()\n\n\nclass inline_ext_function(ext_tools.ext_function):\n # Some specialization is needed for inline extension functions\n def function_declaration_code(self):\n code = 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def template_declaration_code(self):\n code = 'template\\n' \\\n 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def parse_tuple_code(self):\n \"\"\" Create code block for PyArg_ParseTuple. Variable declarations\n for all PyObjects are done also.\n\n This code got a lot uglier when I added local_dict...\n \"\"\"\n declare_return = 'PyObject *return_val = NULL;\\n' \\\n 'int exception_occured = 0;\\n' \\\n 'PyObject *py__locals = NULL;\\n' \\\n 'PyObject *py__globals = NULL;\\n'\n\n py_objects = ', '.join(self.arg_specs.py_pointers())\n if py_objects:\n declare_py_objects = 'PyObject ' + py_objects +';\\n'\n else:\n declare_py_objects = ''\n\n py_vars = ' = '.join(self.arg_specs.py_variables())\n if py_vars:\n init_values = py_vars + ' = NULL;\\n\\n'\n else:\n init_values = ''\n\n parse_tuple = 'if(!PyArg_ParseTuple(args,\"OO:compiled_func\",'\\\n '&py__locals,'\\\n '&py__globals))\\n'\\\n ' return NULL;\\n'\n\n return declare_return + declare_py_objects + \\\n init_values + parse_tuple\n\n def arg_declaration_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.declaration_code(inline=1))\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_cleanup_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.cleanup_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_local_dict_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.local_dict_code())\n code = string.join(arg_strings,\"\")\n return code\n\n\n def function_code(self):\n from ext_tools import indent\n decl_code = indent(self.arg_declaration_code(),4)\n cleanup_code = indent(self.arg_cleanup_code(),4)\n function_code = indent(self.code_block,4)\n #local_dict_code = indent(self.arg_local_dict_code(),4)\n\n try_code = 'try \\n' \\\n '{ \\n' \\\n ' PyObject* raw_locals = py_to_raw_dict(' \\\n 'py__locals,\"_locals\");\\n' \\\n ' PyObject* raw_globals = py_to_raw_dict(' \\\n 'py__globals,\"_globals\");\\n' + \\\n ' /* argument conversion code */ \\n' + \\\n decl_code + \\\n ' /* inline code */ \\n' + \\\n function_code + \\\n ' /*I would like to fill in changed ' \\\n 'locals and globals here...*/ \\n' \\\n '\\n} \\n'\n catch_code = \"catch(...) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n \"} \\n\" \n return_code = \" /* cleanup code */ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n \" {\\n \\n\" \\\n \" Py_INCREF(Py_None); \\n\" \\\n \" return_val = Py_None; \\n\" \\\n \" }\\n \\n\" \\\n \" return return_val; \\n\" \\\n \"} \\n\"\n\n all_code = self.function_declaration_code() + \\\n indent(self.parse_tuple_code(),4) + \\\n indent(try_code,4) + \\\n indent(catch_code,4) + \\\n return_code\n\n return all_code\n\n def python_function_definition_code(self):\n args = (self.name, self.name)\n function_decls = '{\"%s\",(PyCFunction)%s , METH_VARARGS},\\n' % args\n return function_decls\n\nclass inline_ext_module(ext_tools.ext_module):\n def __init__(self,name,compiler=''):\n ext_tools.ext_module.__init__(self,name,compiler)\n self._build_information.append(inline_info.inline_info())\n\nfunction_cache = {}\ndef inline(code,arg_names=[],local_dict = None, global_dict = None,\n force = 0,\n compiler='',\n verbose = 0,\n support_code = None,\n customize=None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n \"\"\" Inline C/C++ code within Python scripts.\n\n inline() compiles and executes C/C++ code on the fly. Variables\n in the local and global Python scope are also available in the\n C/C++ code. Values are passed to the C/C++ code by assignment\n much like variables passed are passed into a standard Python\n function. Values are returned from the C/C++ code through a\n special argument called return_val. Also, the contents of\n mutable objects can be changed within the C/C++ code and the\n changes remain after the C code exits and returns to Python.\n\n inline has quite a few options as listed below. Also, the keyword\n arguments for distutils extension modules are accepted to\n specify extra information needed for compiling.\n\n code -- string. A string of valid C++ code. It should not specify a\n return statement. Instead it should assign results that\n need to be returned to Python in the return_val.\n arg_names -- optional. list of strings. A list of Python variable names \n that should be transferred from Python into the C/C++ \n code. It defaults to an empty string.\n local_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the local scope for the\n C/C++ code. If local_dict is not specified the local\n dictionary of the calling function is used.\n global_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the global scope for\n the C/C++ code. If global_dict is not specified the\n global dictionary of the calling function is used.\n force -- optional. 0 or 1. default 0. If 1, the C++ code is\n compiled every time inline is called. This is really\n only useful for debugging, and probably only useful if\n your editing support_code a lot.\n compiler -- optional. string. The name of compiler to use when\n compiling. On windows, it understands 'msvc' and 'gcc'\n as well as all the compiler names understood by\n distutils. On Unix, it'll only understand the values\n understoof by distutils. ( I should add 'gcc' though\n to this).\n\n On windows, the compiler defaults to the Microsoft C++\n compiler. If this isn't available, it looks for mingw32\n (the gcc compiler).\n\n On Unix, it'll probably use the same compiler that was\n used when compiling Python. Cygwin's behavior should be\n similar.\n verbose -- optional. 0,1, or 2. defualt 0. Speficies how much\n much information is printed during the compile phase\n of inlining code. 0 is silent (except on windows with\n msvc where it still prints some garbage). 1 informs\n you when compiling starts, finishes, and how long it\n took. 2 prints out the command lines for the compilation\n process and can be useful if your having problems\n getting code to work. Its handy for finding the name\n of the .cpp file if you need to examine it. verbose has\n no affect if the compilation isn't necessary.\n support_code -- optional. string. A string of valid C++ code declaring\n extra code that might be needed by your compiled\n function. This could be declarations of functions,\n classes, or structures.\n customize -- optional. base_info.custom_info object. An alternative\n way to specifiy support_code, headers, etc. needed by\n the function see the compiler.base_info module for more\n details. (not sure this'll be used much).\n type_factories -- optional. list of type specification factories. These\n guys are what convert Python data types to C/C++ data\n types. If you'd like to use a different set of type\n conversions than the default, specify them here. Look\n in the type conversions section of the main\n documentation for examples.\n auto_downcast -- optional. 0 or 1. default 1. This only affects\n functions that have Numeric arrays as input variables.\n Setting this to 1 will cause all floating point values\n to be cast as float instead of double if all the\n Numeric arrays are of type float. If even one of the\n arrays has type double or double complex, all\n variables maintain there standard types.\n\n Distutils keywords. These are cut and pasted from Greg Ward's\n distutils.extension.Extension class for convenience:\n\n sources : [string]\n list of source filenames, relative to the distribution root\n (where the setup script lives), in Unix form (slash-separated)\n for portability. Source files may be C, C++, SWIG (.i),\n platform-specific resource files, or whatever else is recognized\n by the \"build_ext\" command as source for a Python extension.\n Note: The module_path file is always appended to the front of this\n list\n include_dirs : [string]\n list of directories to search for C/C++ header files (in Unix\n form for portability)\n define_macros : [(name : string, value : string|None)]\n list of macros to define; each macro is defined using a 2-tuple,\n where 'value' is either the string to define it to or None to\n define it without a particular value (equivalent of \"#define\n FOO\" in source or -DFOO on Unix C compiler command line)\n undef_macros : [string]\n list of macros to undefine explicitly\n library_dirs : [string]\n list of directories to search for C/C++ libraries at link time\n libraries : [string]\n list of library names (not filenames or paths) to link against\n runtime_library_dirs : [string]\n list of directories to search for C/C++ libraries at run time\n (for shared extensions, this is when the extension is loaded)\n extra_objects : [string]\n list of extra files to link with (eg. object files not implied\n by 'sources', static library that must be explicitly specified,\n binary resource files, etc.)\n extra_compile_args : [string]\n any extra platform- and compiler-specific information to use\n when compiling the source files in 'sources'. For platforms and\n compilers where \"command line\" makes sense, this is typically a\n list of command-line arguments, but for other platforms it could\n be anything.\n extra_link_args : [string]\n any extra platform- and compiler-specific information to use\n when linking object files together to create the extension (or\n to create a new static Python interpreter). Similar\n interpretation as for 'extra_compile_args'.\n export_symbols : [string]\n list of symbols to be exported from a shared extension. Not\n used on all platforms, and not generally necessary for Python\n extensions, which typically export exactly one symbol: \"init\" +\n extension_name.\n \"\"\"\n # this grabs the local variables from the *previous* call\n # frame -- that is the locals from the function that called\n # inline.\n global function_catalog\n\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n if force:\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n else:\n # 1. try local cache\n try:\n results = apply(function_cache[code],(local_dict,global_dict))\n return results\n except TypeError, msg: \n msg = str(msg).strip()\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n except NameError, msg: \n msg = str(msg).strip()\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise NameError, msg\n except KeyError:\n pass\n # 2. try function catalog\n try:\n results = attempt_function_call(code,local_dict,global_dict)\n # 3. build the function\n except ValueError:\n # compile the library\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n return results\n\ndef attempt_function_call(code,local_dict,global_dict):\n # we try 3 levels here -- a local cache first, then the\n # catalog cache, and then persistent catalog.\n #\n global function_cache\n # 2. try catalog cache.\n function_list = function_catalog.get_functions_fast(code)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except TypeError, msg: # should specify argument types here.\n # This should really have its own error type, instead of\n # checking the beginning of the message, but I don't know\n # how to define that yet.\n msg = str(msg)\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n except NameError, msg: \n msg = str(msg).strip()\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise NameError, msg \n # 3. try persistent catalog\n module_dir = global_dict.get('__file__',None)\n function_list = function_catalog.get_functions(code,module_dir)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except: # should specify argument types here.\n pass\n # if we get here, the function wasn't found\n raise ValueError, 'function with correct signature not found'\n\ndef inline_function_code(code,arg_names,local_dict=None,\n global_dict=None,auto_downcast = 1,\n type_factories=None,compiler=''):\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n import build_tools\n compiler = build_tools.choose_compiler(compiler)\n ext_func.set_compiler(compiler)\n return ext_func.function_code()\n\ndef compile_function(code,arg_names,local_dict,global_dict,\n module_dir,\n compiler='',\n verbose = 0,\n support_code = None,\n customize = None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n # figure out where to store and what to name the extension module\n # that will contain the function.\n #storage_dir = catalog.intermediate_dir()\n module_path = function_catalog.unique_module_name(code,module_dir)\n storage_dir, module_name = os.path.split(module_path)\n mod = inline_ext_module(module_name,compiler)\n\n # create the function. This relies on the auto_downcast and\n # type factories setting\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n mod.add_function(ext_func)\n\n # if customize (a custom_info object), then set the module customization.\n if customize:\n mod.customize = customize\n\n # add the extra \"support code\" needed by the function to the module.\n if support_code:\n mod.customize.add_support_code(support_code)\n \n # compile code in correct location, with the given compiler and verbosity\n # setting. All input keywords are passed through to distutils\n mod.compile(location=storage_dir,compiler=compiler,\n verbose=verbose, **kw)\n\n # import the module and return the function. Make sure\n # the directory where it lives is in the python path.\n try:\n sys.path.insert(0,storage_dir)\n exec 'import ' + module_name\n func = eval(module_name+'.compiled_func')\n finally:\n del sys.path[0]\n return func\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\nif __name__ == \"__main__\":\n test_function()\n", "source_code_before": "# should re-write compiled functions to take a local and global dict\n# as input.\nimport sys,os\nimport ext_tools\nimport string\nimport catalog\nimport inline_info, cxx_info\n\n# not an easy way for the user_path_list to come in here.\n# the PYTHONCOMPILED environment variable offers the most hope.\n\nfunction_catalog = catalog.catalog()\n\n\nclass inline_ext_function(ext_tools.ext_function):\n # Some specialization is needed for inline extension functions\n def function_declaration_code(self):\n code = 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def template_declaration_code(self):\n code = 'template\\n' \\\n 'static PyObject* %s(PyObject*self, PyObject* args)\\n{\\n'\n return code % self.name\n\n def parse_tuple_code(self):\n \"\"\" Create code block for PyArg_ParseTuple. Variable declarations\n for all PyObjects are done also.\n\n This code got a lot uglier when I added local_dict...\n \"\"\"\n declare_return = 'PyObject *return_val = NULL;\\n' \\\n 'int exception_occured = 0;\\n' \\\n 'PyObject *py__locals = NULL;\\n' \\\n 'PyObject *py__globals = NULL;\\n'\n\n py_objects = ', '.join(self.arg_specs.py_pointers())\n if py_objects:\n declare_py_objects = 'PyObject ' + py_objects +';\\n'\n else:\n declare_py_objects = ''\n\n py_vars = ' = '.join(self.arg_specs.py_variables())\n if py_vars:\n init_values = py_vars + ' = NULL;\\n\\n'\n else:\n init_values = ''\n\n parse_tuple = 'if(!PyArg_ParseTuple(args,\"OO:compiled_func\",'\\\n '&py__locals,'\\\n '&py__globals))\\n'\\\n ' return NULL;\\n'\n\n return declare_return + declare_py_objects + \\\n init_values + parse_tuple\n\n def arg_declaration_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.declaration_code(inline=1))\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_cleanup_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.cleanup_code())\n code = string.join(arg_strings,\"\")\n return code\n\n def arg_local_dict_code(self):\n arg_strings = []\n for arg in self.arg_specs:\n arg_strings.append(arg.local_dict_code())\n code = string.join(arg_strings,\"\")\n return code\n\n\n def function_code(self):\n from ext_tools import indent\n decl_code = indent(self.arg_declaration_code(),4)\n cleanup_code = indent(self.arg_cleanup_code(),4)\n function_code = indent(self.code_block,4)\n #local_dict_code = indent(self.arg_local_dict_code(),4)\n\n try_code = 'try \\n' \\\n '{ \\n' \\\n ' PyObject* raw_locals = py_to_raw_dict(' \\\n 'py__locals,\"_locals\");\\n' \\\n ' PyObject* raw_globals = py_to_raw_dict(' \\\n 'py__globals,\"_globals\");\\n' + \\\n ' /* argument conversion code */ \\n' + \\\n decl_code + \\\n ' /* inline code */ \\n' + \\\n function_code + \\\n ' /*I would like to fill in changed ' \\\n 'locals and globals here...*/ \\n' \\\n '\\n} \\n'\n catch_code = \"catch(...) \\n\" \\\n \"{ \\n\" + \\\n \" return_val = Py::Null(); \\n\" \\\n \" exception_occured = 1; \\n\" \\\n \"} \\n\" \n return_code = \" /* cleanup code */ \\n\" + \\\n cleanup_code + \\\n \" if(!return_val && !exception_occured)\\n\" \\\n \" {\\n \\n\" \\\n \" Py_INCREF(Py_None); \\n\" \\\n \" return_val = Py_None; \\n\" \\\n \" }\\n \\n\" \\\n \" return return_val; \\n\" \\\n \"} \\n\"\n\n all_code = self.function_declaration_code() + \\\n indent(self.parse_tuple_code(),4) + \\\n indent(try_code,4) + \\\n indent(catch_code,4) + \\\n return_code\n\n return all_code\n\n def python_function_definition_code(self):\n args = (self.name, self.name)\n function_decls = '{\"%s\",(PyCFunction)%s , METH_VARARGS},\\n' % args\n return function_decls\n\nclass inline_ext_module(ext_tools.ext_module):\n def __init__(self,name,compiler=''):\n ext_tools.ext_module.__init__(self,name,compiler)\n self._build_information.append(inline_info.inline_info())\n\nfunction_cache = {}\ndef inline(code,arg_names=[],local_dict = None, global_dict = None,\n force = 0,\n compiler='',\n verbose = 0,\n support_code = None,\n customize=None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n \"\"\" Inline C/C++ code within Python scripts.\n\n inline() compiles and executes C/C++ code on the fly. Variables\n in the local and global Python scope are also available in the\n C/C++ code. Values are passed to the C/C++ code by assignment\n much like variables passed are passed into a standard Python\n function. Values are returned from the C/C++ code through a\n special argument called return_val. Also, the contents of\n mutable objects can be changed within the C/C++ code and the\n changes remain after the C code exits and returns to Python.\n\n inline has quite a few options as listed below. Also, the keyword\n arguments for distutils extension modules are accepted to\n specify extra information needed for compiling.\n\n code -- string. A string of valid C++ code. It should not specify a\n return statement. Instead it should assign results that\n need to be returned to Python in the return_val.\n arg_names -- optional. list of strings. A list of Python variable names \n that should be transferred from Python into the C/C++ \n code. It defaults to an empty string.\n local_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the local scope for the\n C/C++ code. If local_dict is not specified the local\n dictionary of the calling function is used.\n global_dict -- optional. dictionary. If specified, it is a dictionary\n of values that should be used as the global scope for\n the C/C++ code. If global_dict is not specified the\n global dictionary of the calling function is used.\n force -- optional. 0 or 1. default 0. If 1, the C++ code is\n compiled every time inline is called. This is really\n only useful for debugging, and probably only useful if\n your editing support_code a lot.\n compiler -- optional. string. The name of compiler to use when\n compiling. On windows, it understands 'msvc' and 'gcc'\n as well as all the compiler names understood by\n distutils. On Unix, it'll only understand the values\n understoof by distutils. ( I should add 'gcc' though\n to this).\n\n On windows, the compiler defaults to the Microsoft C++\n compiler. If this isn't available, it looks for mingw32\n (the gcc compiler).\n\n On Unix, it'll probably use the same compiler that was\n used when compiling Python. Cygwin's behavior should be\n similar.\n verbose -- optional. 0,1, or 2. defualt 0. Speficies how much\n much information is printed during the compile phase\n of inlining code. 0 is silent (except on windows with\n msvc where it still prints some garbage). 1 informs\n you when compiling starts, finishes, and how long it\n took. 2 prints out the command lines for the compilation\n process and can be useful if your having problems\n getting code to work. Its handy for finding the name\n of the .cpp file if you need to examine it. verbose has\n no affect if the compilation isn't necessary.\n support_code -- optional. string. A string of valid C++ code declaring\n extra code that might be needed by your compiled\n function. This could be declarations of functions,\n classes, or structures.\n customize -- optional. base_info.custom_info object. An alternative\n way to specifiy support_code, headers, etc. needed by\n the function see the compiler.base_info module for more\n details. (not sure this'll be used much).\n type_factories -- optional. list of type specification factories. These\n guys are what convert Python data types to C/C++ data\n types. If you'd like to use a different set of type\n conversions than the default, specify them here. Look\n in the type conversions section of the main\n documentation for examples.\n auto_downcast -- optional. 0 or 1. default 1. This only affects\n functions that have Numeric arrays as input variables.\n Setting this to 1 will cause all floating point values\n to be cast as float instead of double if all the\n Numeric arrays are of type float. If even one of the\n arrays has type double or double complex, all\n variables maintain there standard types.\n\n Distutils keywords. These are cut and pasted from Greg Ward's\n distutils.extension.Extension class for convenience:\n\n sources : [string]\n list of source filenames, relative to the distribution root\n (where the setup script lives), in Unix form (slash-separated)\n for portability. Source files may be C, C++, SWIG (.i),\n platform-specific resource files, or whatever else is recognized\n by the \"build_ext\" command as source for a Python extension.\n Note: The module_path file is always appended to the front of this\n list\n include_dirs : [string]\n list of directories to search for C/C++ header files (in Unix\n form for portability)\n define_macros : [(name : string, value : string|None)]\n list of macros to define; each macro is defined using a 2-tuple,\n where 'value' is either the string to define it to or None to\n define it without a particular value (equivalent of \"#define\n FOO\" in source or -DFOO on Unix C compiler command line)\n undef_macros : [string]\n list of macros to undefine explicitly\n library_dirs : [string]\n list of directories to search for C/C++ libraries at link time\n libraries : [string]\n list of library names (not filenames or paths) to link against\n runtime_library_dirs : [string]\n list of directories to search for C/C++ libraries at run time\n (for shared extensions, this is when the extension is loaded)\n extra_objects : [string]\n list of extra files to link with (eg. object files not implied\n by 'sources', static library that must be explicitly specified,\n binary resource files, etc.)\n extra_compile_args : [string]\n any extra platform- and compiler-specific information to use\n when compiling the source files in 'sources'. For platforms and\n compilers where \"command line\" makes sense, this is typically a\n list of command-line arguments, but for other platforms it could\n be anything.\n extra_link_args : [string]\n any extra platform- and compiler-specific information to use\n when linking object files together to create the extension (or\n to create a new static Python interpreter). Similar\n interpretation as for 'extra_compile_args'.\n export_symbols : [string]\n list of symbols to be exported from a shared extension. Not\n used on all platforms, and not generally necessary for Python\n extensions, which typically export exactly one symbol: \"init\" +\n extension_name.\n \"\"\"\n # this grabs the local variables from the *previous* call\n # frame -- that is the locals from the function that called\n # inline.\n global function_catalog\n\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n if force:\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n else:\n # 1. try local cache\n try:\n results = apply(function_cache[code],(local_dict,global_dict))\n return results\n except TypeError, msg: # should specify argument types here.\n msg = str(msg)\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n except KeyError:\n pass\n # 2. try function catalog\n try:\n results = attempt_function_call(code,local_dict,global_dict)\n # 3. build the function\n except ValueError:\n # compile the library\n module_dir = global_dict.get('__file__',None)\n func = compile_function(code,arg_names,local_dict,\n global_dict,module_dir,\n compiler=compiler,\n verbose=verbose,\n support_code = support_code,\n customize=customize,\n type_factories = type_factories,\n auto_downcast = auto_downcast,\n **kw)\n\n function_catalog.add_function(code,func,module_dir)\n results = attempt_function_call(code,local_dict,global_dict)\n return results\n\ndef attempt_function_call(code,local_dict,global_dict):\n # we try 3 levels here -- a local cache first, then the\n # catalog cache, and then persistent catalog.\n #\n global function_cache\n # 2. try catalog cache.\n function_list = function_catalog.get_functions_fast(code)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except TypeError, msg: # should specify argument types here.\n # This should really have its own error type, instead of\n # checking the beginning of the message, but I don't know\n # how to define that yet.\n msg = str(msg)\n if msg[:16] == \"Conversion Error\":\n pass\n else:\n raise TypeError, msg\n \n # 3. try persistent catalog\n module_dir = global_dict.get('__file__',None)\n function_list = function_catalog.get_functions(code,module_dir)\n for func in function_list:\n try:\n results = apply(func,(local_dict,global_dict))\n function_catalog.fast_cache(code,func)\n function_cache[code] = func\n return results\n except: # should specify argument types here.\n pass\n # if we get here, the function wasn't found\n raise ValueError, 'function with correct signature not found'\n\ndef inline_function_code(code,arg_names,local_dict=None,\n global_dict=None,auto_downcast = 1,\n type_factories=None,compiler=''):\n call_frame = sys._getframe().f_back\n if local_dict is None:\n local_dict = call_frame.f_locals\n if global_dict is None:\n global_dict = call_frame.f_globals\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n import build_tools\n compiler = build_tools.choose_compiler(compiler)\n ext_func.set_compiler(compiler)\n return ext_func.function_code()\n\ndef compile_function(code,arg_names,local_dict,global_dict,\n module_dir,\n compiler='',\n verbose = 0,\n support_code = None,\n customize = None,\n type_factories = None,\n auto_downcast=1,\n **kw):\n # figure out where to store and what to name the extension module\n # that will contain the function.\n #storage_dir = catalog.intermediate_dir()\n module_path = function_catalog.unique_module_name(code,module_dir)\n storage_dir, module_name = os.path.split(module_path)\n mod = inline_ext_module(module_name,compiler)\n\n # create the function. This relies on the auto_downcast and\n # type factories setting\n ext_func = inline_ext_function('compiled_func',code,arg_names,\n local_dict,global_dict,auto_downcast,\n type_factories = type_factories)\n mod.add_function(ext_func)\n\n # if customize (a custom_info object), then set the module customization.\n if customize:\n mod.customize = customize\n\n # add the extra \"support code\" needed by the function to the module.\n if support_code:\n mod.customize.add_support_code(support_code)\n \n # compile code in correct location, with the given compiler and verbosity\n # setting. All input keywords are passed through to distutils\n mod.compile(location=storage_dir,compiler=compiler,\n verbose=verbose, **kw)\n\n # import the module and return the function. Make sure\n # the directory where it lives is in the python path.\n try:\n sys.path.insert(0,storage_dir)\n exec 'import ' + module_name\n func = eval(module_name+'.compiled_func')\n finally:\n del sys.path[0]\n return func\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n\nif __name__ == \"__main__\":\n test_function()\n", "methods": [ { "name": "function_declaration_code", "long_name": "function_declaration_code( self )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 17, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "template_declaration_code", "long_name": "template_declaration_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 16, "parameters": [ "self" ], "start_line": 21, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "parse_tuple_code", "long_name": "parse_tuple_code( self )", "filename": "inline_tools.py", "nloc": 21, "complexity": 3, "token_count": 89, "parameters": [ "self" ], "start_line": 26, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "arg_declaration_code", "long_name": "arg_declaration_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 41, "parameters": [ "self" ], "start_line": 57, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_cleanup_code", "long_name": "arg_cleanup_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 64, "end_line": 69, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_local_dict_code", "long_name": "arg_local_dict_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 71, "end_line": 76, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "inline_tools.py", "nloc": 38, "complexity": 1, "token_count": 148, "parameters": [ "self" ], "start_line": 79, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 122, "end_line": 125, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , compiler = '' )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 35, "parameters": [ "self", "name", "compiler" ], "start_line": 128, "end_line": 130, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "inline", "long_name": "inline( code , arg_names = [ ] , local_dict = None , global_dict = None , force = 0 , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 62, "complexity": 10, "token_count": 330, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "force", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 133, "end_line": 332, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 200, "top_nesting_level": 0 }, { "name": "attempt_function_call", "long_name": "attempt_function_call( code , local_dict , global_dict )", "filename": "inline_tools.py", "nloc": 32, "complexity": 8, "token_count": 174, "parameters": [ "code", "local_dict", "global_dict" ], "start_line": 334, "end_line": 374, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 41, "top_nesting_level": 0 }, { "name": "inline_function_code", "long_name": "inline_function_code( code , arg_names , local_dict = None , global_dict = None , auto_downcast = 1 , type_factories = None , compiler = '' )", "filename": "inline_tools.py", "nloc": 15, "complexity": 3, "token_count": 98, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "auto_downcast", "type_factories", "compiler" ], "start_line": 376, "end_line": 390, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "compile_function", "long_name": "compile_function( code , arg_names , local_dict , global_dict , module_dir , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 29, "complexity": 4, "token_count": 169, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "module_dir", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 392, "end_line": 436, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 45, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 438, "end_line": 440, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 442, "end_line": 444, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "function_declaration_code", "long_name": "function_declaration_code( self )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [ "self" ], "start_line": 17, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "template_declaration_code", "long_name": "template_declaration_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 16, "parameters": [ "self" ], "start_line": 21, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "parse_tuple_code", "long_name": "parse_tuple_code( self )", "filename": "inline_tools.py", "nloc": 21, "complexity": 3, "token_count": 89, "parameters": [ "self" ], "start_line": 26, "end_line": 55, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 30, "top_nesting_level": 1 }, { "name": "arg_declaration_code", "long_name": "arg_declaration_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 41, "parameters": [ "self" ], "start_line": 57, "end_line": 62, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_cleanup_code", "long_name": "arg_cleanup_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 64, "end_line": 69, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "arg_local_dict_code", "long_name": "arg_local_dict_code( self )", "filename": "inline_tools.py", "nloc": 6, "complexity": 2, "token_count": 38, "parameters": [ "self" ], "start_line": 71, "end_line": 76, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 6, "top_nesting_level": 1 }, { "name": "function_code", "long_name": "function_code( self )", "filename": "inline_tools.py", "nloc": 38, "complexity": 1, "token_count": 148, "parameters": [ "self" ], "start_line": 79, "end_line": 120, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 42, "top_nesting_level": 1 }, { "name": "python_function_definition_code", "long_name": "python_function_definition_code( self )", "filename": "inline_tools.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self" ], "start_line": 122, "end_line": 125, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "__init__", "long_name": "__init__( self , name , compiler = '' )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 35, "parameters": [ "self", "name", "compiler" ], "start_line": 128, "end_line": 130, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "inline", "long_name": "inline( code , arg_names = [ ] , local_dict = None , global_dict = None , force = 0 , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 56, "complexity": 8, "token_count": 295, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "force", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 133, "end_line": 326, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 194, "top_nesting_level": 0 }, { "name": "attempt_function_call", "long_name": "attempt_function_call( code , local_dict , global_dict )", "filename": "inline_tools.py", "nloc": 26, "complexity": 6, "token_count": 143, "parameters": [ "code", "local_dict", "global_dict" ], "start_line": 328, "end_line": 363, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 36, "top_nesting_level": 0 }, { "name": "inline_function_code", "long_name": "inline_function_code( code , arg_names , local_dict = None , global_dict = None , auto_downcast = 1 , type_factories = None , compiler = '' )", "filename": "inline_tools.py", "nloc": 15, "complexity": 3, "token_count": 98, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "auto_downcast", "type_factories", "compiler" ], "start_line": 365, "end_line": 379, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 15, "top_nesting_level": 0 }, { "name": "compile_function", "long_name": "compile_function( code , arg_names , local_dict , global_dict , module_dir , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 29, "complexity": 4, "token_count": 169, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "module_dir", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 381, "end_line": 425, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 45, "top_nesting_level": 0 }, { "name": "test", "long_name": "test( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 427, "end_line": 429, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "inline_tools.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 431, "end_line": 433, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "changed_methods": [ { "name": "inline", "long_name": "inline( code , arg_names = [ ] , local_dict = None , global_dict = None , force = 0 , compiler = '' , verbose = 0 , support_code = None , customize = None , type_factories = None , auto_downcast = 1 , ** kw )", "filename": "inline_tools.py", "nloc": 62, "complexity": 10, "token_count": 330, "parameters": [ "code", "arg_names", "local_dict", "global_dict", "force", "compiler", "verbose", "support_code", "customize", "type_factories", "auto_downcast", "kw" ], "start_line": 133, "end_line": 332, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 200, "top_nesting_level": 0 }, { "name": "attempt_function_call", "long_name": "attempt_function_call( code , local_dict , global_dict )", "filename": "inline_tools.py", "nloc": 32, "complexity": 8, "token_count": 174, "parameters": [ "code", "local_dict", "global_dict" ], "start_line": 334, "end_line": 374, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 41, "top_nesting_level": 0 } ], "nloc": 246, "complexity": 41, "token_count": 1306, "diff_parsed": { "added": [ " except TypeError, msg:", " msg = str(msg).strip()", " except NameError, msg:", " msg = str(msg).strip()", " if msg[:16] == \"Conversion Error\":", " pass", " else:", " raise NameError, msg", " except NameError, msg:", " msg = str(msg).strip()", " if msg[:16] == \"Conversion Error\":", " pass", " else:", " raise NameError, msg" ], "deleted": [ " except TypeError, msg: # should specify argument types here.", " msg = str(msg)", "" ] } }, { "old_path": "weave/sequence_spec.py", "new_path": "weave/sequence_spec.py", "filename": "sequence_spec.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -54,7 +54,7 @@ def type_match(self,value):\n \n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n- code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\\n+ code = 'Py::Dict %s = convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n@@ -75,3 +75,11 @@ def declaration_code(self,templatize = 0,inline=0):\n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n+\n+def test():\n+ from scipy_test import module_test\n+ module_test(__name__,__file__)\n+\n+def test_suite():\n+ from scipy_test import module_test_suite\n+ return module_test_suite(__name__,__file__) \n", "added_lines": 9, "deleted_lines": 1, "source_code": "import cxx_info\nfrom base_spec import base_specification\nfrom types import *\nimport os\n\nclass base_cxx_specification(base_specification):\n _build_information = [cxx_info.cxx_info()]\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(%s:: name: %s)\" % (self.type_name,self.name)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \nclass string_specification(base_cxx_specification):\n type_name = 'string'\n def type_match(self,value):\n return type(value) in [StringType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\n\nclass list_specification(base_cxx_specification):\n type_name = 'list'\n def type_match(self,value):\n return type(value) in [ListType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass dict_specification(base_cxx_specification):\n type_name = 'dict'\n def type_match(self,value):\n return type(value) in [DictType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Dict %s = convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass tuple_specification(base_cxx_specification):\n type_name = 'tuple'\n def type_match(self,value):\n return type(value) in [TupleType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\ndef test():\n from scipy_test import module_test\n module_test(__name__,__file__)\n\ndef test_suite():\n from scipy_test import module_test_suite\n return module_test_suite(__name__,__file__) \n", "source_code_before": "import cxx_info\nfrom base_spec import base_specification\nfrom types import *\nimport os\n\nclass base_cxx_specification(base_specification):\n _build_information = [cxx_info.cxx_info()]\n def type_spec(self,name,value):\n # factory\n new_spec = self.__class__()\n new_spec.name = name \n return new_spec\n def __repr__(self):\n msg = \"(%s:: name: %s)\" % (self.type_name,self.name)\n return msg\n def __cmp__(self,other):\n #only works for equal\n return cmp(self.name,other.name) or \\\n cmp(self.__class__, other.__class__)\n \nclass string_specification(base_cxx_specification):\n type_name = 'string'\n def type_match(self,value):\n return type(value) in [StringType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::String %s = convert_to_string(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\n\nclass list_specification(base_cxx_specification):\n type_name = 'list'\n def type_match(self,value):\n return type(value) in [ListType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::List %s = convert_to_list(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass dict_specification(base_cxx_specification):\n type_name = 'dict'\n def type_match(self,value):\n return type(value) in [DictType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name) \n return code\n \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n\nclass tuple_specification(base_cxx_specification):\n type_name = 'tuple'\n def type_match(self,value):\n return type(value) in [TupleType]\n\n def declaration_code(self,templatize = 0,inline=0):\n var_name = self.retrieve_py_variable(inline)\n code = 'Py::Tuple %s = convert_to_tuple(%s,\"%s\");\\n' % \\\n (self.name,var_name,self.name)\n return code \n def local_dict_code(self):\n code = 'local_dict[\"%s\"] = %s;\\n' % (self.name,self.name) \n return code\n", "methods": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "sequence_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 8, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 16, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 23, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 38, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 41, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 46, "end_line": 48, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 52, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 67, "end_line": 68, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 70, "end_line": 74, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 75, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 79, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "test_suite", "long_name": "test_suite( )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 83, "end_line": 85, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "methods_before": [ { "name": "type_spec", "long_name": "type_spec( self , name , value )", "filename": "sequence_spec.py", "nloc": 4, "complexity": 1, "token_count": 23, "parameters": [ "self", "name", "value" ], "start_line": 8, "end_line": 12, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "__repr__", "long_name": "__repr__( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 13, "end_line": 15, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "__cmp__", "long_name": "__cmp__( self , other )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 2, "token_count": 30, "parameters": [ "self", "other" ], "start_line": 16, "end_line": 19, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 4, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 23, "end_line": 24, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 26, "end_line": 30, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 31, "end_line": 33, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 38, "end_line": 39, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 41, "end_line": 45, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 46, "end_line": 48, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 52, "end_line": 53, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 61, "end_line": 63, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 }, { "name": "type_match", "long_name": "type_match( self , value )", "filename": "sequence_spec.py", "nloc": 2, "complexity": 1, "token_count": 16, "parameters": [ "self", "value" ], "start_line": 67, "end_line": 68, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 2, "top_nesting_level": 1 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 70, "end_line": 74, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "local_dict_code", "long_name": "local_dict_code( self )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 20, "parameters": [ "self" ], "start_line": 75, "end_line": 77, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 1 } ], "changed_methods": [ { "name": "test_suite", "long_name": "test_suite( )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 15, "parameters": [], "start_line": 83, "end_line": 85, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 }, { "name": "declaration_code", "long_name": "declaration_code( self , templatize = 0 , inline = 0 )", "filename": "sequence_spec.py", "nloc": 5, "complexity": 1, "token_count": 39, "parameters": [ "self", "templatize", "inline" ], "start_line": 55, "end_line": 59, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 5, "top_nesting_level": 1 }, { "name": "test", "long_name": "test( )", "filename": "sequence_spec.py", "nloc": 3, "complexity": 1, "token_count": 14, "parameters": [], "start_line": 79, "end_line": 81, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 3, "top_nesting_level": 0 } ], "nloc": 70, "complexity": 18, "token_count": 482, "diff_parsed": { "added": [ " code = 'Py::Dict %s = convert_to_dict(%s,\"%s\");\\n' % \\", "", "def test():", " from scipy_test import module_test", " module_test(__name__,__file__)", "", "def test_suite():", " from scipy_test import module_test_suite", " return module_test_suite(__name__,__file__)" ], "deleted": [ " code = 'Py::Dict %s = x__dict_handler.convert_to_dict(%s,\"%s\");\\n' % \\" ] } } ] }, { "hash": "c604a3821cf1114c63dc719aae36ebe262d7d303", "msg": "bumped version number to 0.2.3", "author": { "name": "Eric Jones", "email": "eric@enthought.com" }, "committer": { "name": "Eric Jones", "email": "eric@enthought.com" }, "author_date": "2002-01-22T22:27:48+00:00", "author_timezone": 0, "committer_date": "2002-01-22T22:27:48+00:00", "committer_timezone": 0, "branches": [ "main" ], "in_main_branch": true, "merge": false, "parents": [ "227c397f7f597f58dc068e98021d4805b667e642" ], "project_name": "repo_copy", "project_path": "/tmp/tmp55a0ktwg/repo_copy", "deletions": 1, "insertions": 1, "lines": 2, "files": 1, "dmm_unit_size": null, "dmm_unit_complexity": null, "dmm_unit_interfacing": null, "modified_files": [ { "old_path": "weave/setup.py", "new_path": "weave/setup.py", "filename": "setup.py", "extension": "py", "change_type": "MODIFY", "diff": "@@ -6,7 +6,7 @@\n \n # Enought changes to bump the number. We need a global method for\n # versioning\n-version = \"0.2\"\n+version = \"0.2.3\"\n \n def stand_alone_package(with_dependencies = 0):\n path = get_path(__name__)\n", "added_lines": 1, "deleted_lines": 1, "source_code": "#!/usr/bin/env python\nimport os,sys\nfrom scipy_distutils.core import setup\nfrom scipy_distutils.misc_util import get_path, merge_config_dicts\nfrom scipy_distutils.misc_util import package_config\n\n# Enought changes to bump the number. We need a global method for\n# versioning\nversion = \"0.2.3\"\n \ndef stand_alone_package(with_dependencies = 0):\n path = get_path(__name__)\n old_path = os.getcwd()\n os.chdir(path)\n try:\n primary = ['weave']\n if with_dependencies:\n dependencies= ['scipy_distutils', 'scipy_test'] \n else:\n dependencies = [] \n \n print 'dep:', dependencies\n config_dict = package_config(primary,dependencies)\n\n setup (name = \"weave\",\n version = version,\n description = \"Tools for inlining C/C++ in Python\",\n author = \"Eric Jones\",\n author_email = \"eric@enthought.com\",\n licence = \"SciPy License (BSD Style)\",\n url = 'http://www.scipy.org',\n **config_dict\n ) \n finally:\n os.chdir(old_path)\n\nif __name__ == '__main__':\n import sys\n if '--without-dependencies' in sys.argv:\n with_dependencies = 0\n sys.argv.remove('--without-dependencies')\n else:\n with_dependencies = 1 \n stand_alone_package(with_dependencies)\n \n", "source_code_before": "#!/usr/bin/env python\nimport os,sys\nfrom scipy_distutils.core import setup\nfrom scipy_distutils.misc_util import get_path, merge_config_dicts\nfrom scipy_distutils.misc_util import package_config\n\n# Enought changes to bump the number. We need a global method for\n# versioning\nversion = \"0.2\"\n \ndef stand_alone_package(with_dependencies = 0):\n path = get_path(__name__)\n old_path = os.getcwd()\n os.chdir(path)\n try:\n primary = ['weave']\n if with_dependencies:\n dependencies= ['scipy_distutils', 'scipy_test'] \n else:\n dependencies = [] \n \n print 'dep:', dependencies\n config_dict = package_config(primary,dependencies)\n\n setup (name = \"weave\",\n version = version,\n description = \"Tools for inlining C/C++ in Python\",\n author = \"Eric Jones\",\n author_email = \"eric@enthought.com\",\n licence = \"SciPy License (BSD Style)\",\n url = 'http://www.scipy.org',\n **config_dict\n ) \n finally:\n os.chdir(old_path)\n\nif __name__ == '__main__':\n import sys\n if '--without-dependencies' in sys.argv:\n with_dependencies = 0\n sys.argv.remove('--without-dependencies')\n else:\n with_dependencies = 1 \n stand_alone_package(with_dependencies)\n \n", "methods": [ { "name": "stand_alone_package", "long_name": "stand_alone_package( with_dependencies = 0 )", "filename": "setup.py", "nloc": 23, "complexity": 3, "token_count": 102, "parameters": [ "with_dependencies" ], "start_line": 11, "end_line": 35, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 0 } ], "methods_before": [ { "name": "stand_alone_package", "long_name": "stand_alone_package( with_dependencies = 0 )", "filename": "setup.py", "nloc": 23, "complexity": 3, "token_count": 102, "parameters": [ "with_dependencies" ], "start_line": 11, "end_line": 35, "fan_in": 0, "fan_out": 0, "general_fan_out": 0, "length": 25, "top_nesting_level": 0 } ], "changed_methods": [], "nloc": 36, "complexity": 3, "token_count": 164, "diff_parsed": { "added": [ "version = \"0.2.3\"" ], "deleted": [ "version = \"0.2\"" ] } } ] } ]